Chapter 7: Decision Making and Looping
- LO 7.1: Understand the concept of looping and the while statement
- LO 7.2: Implement do-while loops for exit-controlled looping
- LO 7.3: Use the for statement with various options
- LO 7.4: Apply jumps in loops using break, continue, and goto
7.1 Introduction to Looping
A program loop consists of two segments: the body of the loop and the control statement. The control statement tests certain conditions and directs the repeated execution of the statements in the body of the loop.
Types of loops:
- Entry-controlled loop (pre-test): Condition is tested before loop execution. If condition fails, body is not executed. (while, for)
- Exit-controlled loop (post-test): Condition is tested at the end. Body is executed at least once. (do-while)
Entry-Controlled Exit-Controlled
(while, for) (do-while)
βββββββββββββββββββ βββββββββββββββββββ
β Condition β β Loop Body β
ββββββββββ¬βββββββββ ββββββββββ¬βββββββββ
β β
FalseβTrue β
β β
βββββββββββββββββββ βββββββββββββββββββ
β Loop Body β β Condition β
βββββββββββββββββββ ββββββββββ¬βββββββββ
β β
βββββββββ Trueβ False
β β β
β β
βββββββββββββββββββ βββββββββββββββββββ
β Next Statement β β Next Statement β
βββββββββββββββββββ βββββββββββββββββββ
Fig. 7.1: Entry-controlled vs Exit-controlled loops
A looping process generally includes four steps:
- Setting and initialization of a condition variable
- Execution of the statements in the loop
- Test for a specified value of the condition variable
- Incrementing or updating the condition variable
7.2 The while Statement
The while statement is an entry-controlled loop. It tests the condition before executing the loop body.
while (test-condition)
{
body of the loop;
}
π Worked-Out Problem 7.1
Computing x to the power n using while loop:
#include <stdio.h>
int main() {
int count = 1, n;
float x, y = 1;
printf("Enter the values of x and n: ");
scanf("%f %d", &x, &n);
while (count <= n) {
y = y * x;
count++;
}
printf("%.2f to the power %d = %.2f\n", x, n, y);
return 0;
}
Enter the values of x and n: 2.5 4
2.50 to the power 4 = 39.06
π Worked-Out Problem 7.2
Converting days to months and days (using while):
#include <stdio.h>
int main() {
int days, months;
printf("Enter number of days: ");
scanf("%d", &days);
months = days / 30;
days = days % 30;
printf("Months = %d, Days = %d\n", months, days);
return 0;
}
Enter number of days: 75
Months = 2, Days = 15
7.3 The do-while Statement
The do-while statement is an exit-controlled loop. The body of the loop is executed at least once, then the condition is tested.
do
{
body of the loop;
} while (test-condition);
π Worked-Out Problem 7.3
Multiplication table using do-while:
#include <stdio.h>
int main() {
int num, i = 1;
printf("Enter a number: ");
scanf("%d", &num);
do {
printf("%d Γ %d = %d\n", num, i, num * i);
i++;
} while (i <= 10);
return 0;
}
Enter a number: 7
7 Γ 1 = 7
7 Γ 2 = 14
7 Γ 3 = 21
...
7 Γ 10 = 70
7.4 The for Statement
The for loop is an entry-controlled loop that provides a more concise loop control structure. It combines initialization, condition testing, and increment/decrement in one line.
for (initialization; test-condition; increment)
{
body of the loop;
}
π Worked-Out Problem 7.4
Printing 'Power of 2' table using for loop:
#include <stdio.h>
int main() {
long int p;
int n;
double q;
printf("2 to power n n 2 to power -n\n");
for (p = 1, n = 0; n < 10; ++n) {
if (n == 0)
p = 1;
else
p = p * 2;
q = 1.0 / (double)p;
printf("%10ld %10d %20.12lf\n", p, n, q);
}
return 0;
}
2 to power n n 2 to power -n
1 0 1.000000000000
2 1 0.500000000000
4 2 0.250000000000
8 3 0.125000000000
16 4 0.062500000000
...
Additional Features of for Loop
- Multiple initializations:
for (p = 1, n = 0; n < 17; ++n) - Compound test conditions:
for (i = 0; i < 20 && sum < 100; i++) - Omitted sections: Any or all sections can be omitted, but semicolons must remain
- Infinite loop:
for (;;)creates an infinite loop - Null statement:
for (j = 1000; j > 0; j--);creates a time delay loop
π Worked-Out Problem 7.5
Printing all prime numbers between 1 and n:
#include <stdio.h>
int prime(int num) {
int i;
if (num < 2) return 0;
for (i = 2; i <= num/2; i++) {
if (num % i == 0)
return 0;
}
return 1;
}
int main() {
int n, i;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Prime numbers between 1 and %d are:\n", n);
for (i = 2; i <= n; i++) {
if (prime(i))
printf("%d ", i);
}
printf("\n");
return 0;
}
Enter the value of n: 20
Prime numbers between 1 and 20 are:
2 3 5 7 11 13 17 19
7.5 Nested Loops
One loop inside another is called nested loops. ANSI C allows up to 15 levels of nesting.
π Worked-Out Problem 7.6
Multiplication table using nested for loops:
#include <stdio.h>
int main() {
int r, c, product;
for (r = 1; r <= 10; r++) {
for (c = 1; c <= 10; c++) {
product = r * c;
printf("%5d", product);
}
printf("\n");
}
return 0;
}
π Worked-Out Problem 7.7
Program to build a pyramid:
#include <stdio.h>
int main() {
int i, j, k;
for (i = 1; i <= 5; i++) {
for (j = i; j < 5; j++)
printf(" ");
for (k = 1; k <= (2*i - 1); k++)
printf("*");
printf("\n");
}
return 0;
}
*
***
*****
*******
*********
7.6 Loop Comparison
| while | do-while | for |
|---|---|---|
| Entry-controlled loop | Exit-controlled loop | Entry-controlled loop |
| Condition tested at beginning | Condition tested at end | Condition tested at beginning |
| May not execute if condition false | Executes at least once | May not execute if condition false |
| Initialization done before loop | Initialization done before loop | Initialization in loop header |
| Increment inside loop body | Increment inside loop body | Increment in loop header |
| All three loops can implement counter-controlled and sentinel-controlled loops | ||
7.7 Jumps in Loops
break Statement
The break statement causes immediate exit from the loop. Program continues with the statement immediately following the loop.
π Worked-Out Problem 7.8
Using break to exit loop early:
#include <stdio.h>
int main() {
int i;
float num, sum = 0;
printf("Enter numbers (enter negative to stop):\n");
for (i = 1; i <= 100; i++) {
scanf("%f", &num);
if (num < 0)
break;
sum += num;
}
printf("Sum = %.2f\n", sum);
printf("Total numbers entered: %d\n", i-1);
return 0;
}
Enter numbers (enter negative to stop):
10 20 30 -1
Sum = 60.00
Total numbers entered: 3
continue Statement
The continue statement skips the remaining statements in the current iteration and continues with the next iteration of the loop.
π Worked-Out Problem 7.9
Using continue to skip processing for negative numbers:
#include <stdio.h>
#include <math.h>
int main() {
int count_neg = 0, count_pos = 0;
float num, sqroot;
printf("Enter numbers (9999 to stop):\n");
while (1) {
scanf("%f", &num);
if (num == 9999)
break;
if (num < 0) {
printf("Number %f is negative. Square root not possible.\n", num);
count_neg++;
continue;
}
sqroot = sqrt(num);
printf("Number: %f\tSquare root: %f\n", num, sqroot);
count_pos++;
}
printf("Positive numbers: %d, Negative numbers: %d\n", count_pos, count_neg);
return 0;
}
goto Statement
The goto statement can transfer control anywhere in a function. It's useful for exiting deeply nested loops.
Using goto makes programs difficult to read and maintain. In structured programming, it's better to use break, continue, and proper loop design.
π Worked-Out Problem 7.10
Using goto to exit nested loops (rare case):
#include <stdio.h>
int main() {
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5; j++) {
if (i * j > 20)
goto out;
printf("%d Γ %d = %d\n", i, j, i*j);
}
}
out:
printf("Exited at i = %d, j = %d\n", i, j);
return 0;
}
7.8 exit() Function
The exit() function terminates program execution immediately and returns control to the operating system.
#include <stdlib.h> exit(0); // Normal termination exit(1); // Termination due to error
7.9 Concise Test Expressions
We can write concise test expressions without relational operators:
if (expression == 0) is equivalent to if (!expression) if (expression != 0) is equivalent to if (expression)
Example: if (m%5 == 0 && n%5 == 0) is same as if (!(m%5) && !(n%5))
- If you need a post-test loop, use
do-while(only choice). - If you need a pre-test loop, choose between
forandwhile. - Use
forfor counter-controlled loops where number of iterations is known. - Use
whilefor sentinel-controlled loops where termination depends on a special value.
Chapter Exercises
Review Questions
- State true or false:
a) In a pretest loop, if the body is executed n times, the test expression is executed n+1 times.
b) Thedo-whilestatement first executes the loop body and then evaluates the loop control expression.
c) An exit-controlled loop is executed a minimum of one time.
d) The three loop expressions in aforloop header must be separated by commas.
e) The use ofcontinuestatement is considered as unstructured programming. - What is a null statement? Explain a typical use of it.
- How would you decide the use of one of the three loops in C for a given problem?
- Explain the operation of the following
forloops:
a)for (n = 1; n != 10; n += 2)
b)for (n = 5; n <= m; n -= 1)
c)for (n = 1; n <= 5;)
Multiple Choice Questions
- Which of the following looping statements end with a semicolon?
a) while
b) do-while
c) for
d) None - A typical repetition control structure comprises which parts?
a) Initialisation of condition variable
b) Execution block
c) Test condition and counter update
d) All of these - Which statement skips the execution of the remaining part of the loop?
a) break
b) continue
c) Both a and b
d) None
Debugging Exercises
Find errors, if any, in the following looping segments:
while (i <= 10); {
sum += i;
i++;
}
do {
scanf("%d", &num);
if (num < 0) break;
sum += num;
} while (i <= 10)
for (i = 0, i < 10, i++)
printf("%d", i);
count = 1;
while (count < 10)
printf("%d", count);
count++;
Programming Exercises
- Given a number, write a program using
whileloop to reverse the digits. (Example: 12345 β 54321) - Write a program to compute the sum of digits of a given integer number.
- The numbers 1 1 2 3 5 8 13 21... are Fibonacci numbers. Write a program using a
do-whileloop to calculate and print the first m Fibonacci numbers. - Write a program to evaluate the investment equation V = P(1+r)^n and print tables for various values.
- Write programs to print the following outputs using
forloops:
a)* ** *** **** *****
b)1 12 123 1234 12345
- Write a program to compute the value of Euler's number e using the formula: e = 1 + 1/1! + 1/2! + 1/3! + ... + 1/n! Stop when the difference between successive values is less than 0.00001.
- Write a program to evaluate sin(x) using the series: sin x = x - xΒ³/3! + xβ΅/5! - xβ·/7! + ...
Interview Questions
- What is the value of variable a after the following code?
int a; for(a=0; a<10; a++) { } - What is the final value of x after:
for(x=9; x>=0; x--) { } - What is the minimum number of times a do-while loop is guaranteed to execute?
- What will be the output of:
i=0; while(i++<5) { if(i==0) printf("Zero\n"); else printf("Hello World\n"); } - Is it possible to print integer values from 1 to 100 without using any looping construct?
Case Study: Table of Binomial Coefficients
π Case Study: Binomial Coefficients Table
#include <stdio.h>
#define MAX 10
int main() {
int m, x, binom;
printf("m x");
for (m = 0; m <= 10; m++)
printf("%4d", m);
printf("\n");
for (m = 0; m <= 10; m++) {
printf("%2d ", m);
binom = 1;
for (x = 0; x <= m; x++) {
if (m == 0 || x == 0)
binom = 1;
else
binom = binom * (m - x + 1) / x;
printf("%4d", binom);
}
printf("\n");
}
return 0;
}