Loop control statements are used when a section of code may either be executed a fixed number of times, or while some condition is true. C gives you a choice of three types of loop statements, while, do- while and for.
The While Loop
When in a program a single statement or a certain group of statements are to be executed repeatedly depending upon certain test condition, then while statement is used. The syntax is as follows:
while (test condition)
{
body_of_the_loop;
}
Here, test condition is an expression that controls how long the loop keeps running. Body of the loop is a statement or group of statements enclosed in braces and are repeatedly executed till the value of test condition evaluates to true. As soon as the condition evaluates to false, the control jumps to the first statement following the while statement. If condition initially itself is false, the body of the loop will never be executed. While loop is sometimes called as entry-control loop, as it controls the execution of the body of the loop depending upon the value of the test condition
The do...while Loop
There is another loop control structure which is very similar to the while statement – called as the do.. while statement. The only difference is that the expression which determines whether to carry on looping is evaluated at the end of each loop. The syntax is as follows:
do
{
statement(s);
} while(test condition);
In do-while loop, the body of loop is executed at least once before the condition is evaluated. Then the loop repeats body as long as condition is true. However, in while loop, the statement doesn’t execute the body of the loop even once, if condition is false. That is why do-while loop is also called exit-control loop.
The for Loop
for statement makes it more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered. The syntax is as follows:
for (initialization; test condition; increment or decrement)
{
Statement(s);
}
The main purpose is to repeat statement while condition remains true, like the while
loop. But in addition, for provides places to specify an initialization instruction and an
increment or decrement of the control variable instruction. So this loop is specially
designed to perform a repetitive action with a counter.
The Nested Loops
C allows loops to be nested, that is, one loop may be inside another. The program given below illustrates the nesting of loops.
Write a program to generate the following pattern given below:
1
1 2
1 2 3
1 2 3 4
/* Program to print the pattern */
int main() {
int i, j;
for (i = 1; i <= 4; ++i) {
printf("%d\n", i);
for (j = 1; j <= i; ++j)
printf("%d\t", j);
}
return 0;
}
Here, an inner for loop is written inside the outer for loop. For every value of i, j
takes the value from 1 to i and then value of i is incremented and next iteration of
outer loop starts ranging j value from 1 to i.