C while, do-while and for Loops

C programming language provides two types of control statements.

  1. Selection or Decision Control Statements – The decision and case control statements allow selective processing of a statement of a group of statements. These are also called as Conditional Statements.
  2. Repetition or Loop Control Statements – The Loop control statement executes a group of statements repeatedly till a condition is satisfied

Statements and blocks

An expression becomes a statement when a semicolon follows it. Braces {and} are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to a single statement. There is no semicolon after the right brace that ends a block.

Repetition or loop control statements

These statements are also called as Iterative Structure or Program Loop. This allows a sequence of program statements to be executed several times, either a specified number of times or until a particular condition is satisfied.

It consists of an entry point that may include initialization of loop variables, a loop continuation condition, a loop body and an exit point.

  1. The while loop
  2. The do-while loop
  3. The for loop

The loop continuation condition may be tested before the loop body is executed as in case of while and for loops. In such case, the loop is referred to as a pre-test loop. The case in which the condition is tested after the execution of the loop body, as in case of dowhile loop, such a loop is called as post-test loop.

The while Loop

The general format of a while loop is:

initialization; 
while (expression) 
{ 
    statements; 
}

The expression is evaluated first. If the expression evaluates to non-zero (true), the body of the loop is executed. After execution of the body, the expression is once again evaluated and if it is true, the body of the loop is executed once again.

This process continues until the result of the expression becomes zero (false). The iteration is then terminated and the control passes to the first statement that follows the body of the while loop. If the expression evaluates to zero (false) at the very first time, the body of the loop is not executed even once.

/* Program to print numbers 1 to 10 using while loop */ 
void main(void) 
{ 
   int num = 1; 
   while (num <= 10) 
  { 
     printf(“%d \n”, num); 
     num++; 
  } 
}

The do…while loop

The general format of a do…while loop is:

initialization; 
do 
{ 
    statement-block; 
} 
while (expression);

In case of do…while loop, the body of the loop is executed, followed by the evaluation of the expression. If the expression evaluates to non-zero (true) the body of the loop is again executed. The iteration continues until the expression evaluates to zero (false). The iteration is then terminated. If the expression evaluates to zero (false) at the very first time, the body of the loop is already executed once.

/* Program to print numbers 1 to 10 using do…while loop */ 
void main(void) 
{ 
   int num = 1; 
   do 
   { 
      printf(“%d \n”, num++); 
   }  
   while (num <= 10); 
}
Note: Since the exit condition is evaluated at the bottom of the loop, in case of do…while, the body of the loop is executed at least once

In case of while and do…while loops, the loop counter is initialized before the control enters the loop and it must be incremented/decremented within the body of the loop.

The for Loop

The for loop is very flexible and is preferable when there is a simple initialization and increment, as it keeps the loop control statements close together and visible at the top of the loop.

The general format of the for loop is:

for (expr1; expr2; expr3) 
{ 
   statement-block; 
}

This is equivalent to:

expr1; 
while (expr2) 
{ 
   statement-block; 
   expr3; 
}

The three components of for loop are expressions. Most commonly, expr1 (initialization) and expr3 (increment) are assignments or function calls and expr2 (test condition) is a relational expression.

The sequence of control flow or the evaluation of these three expressions is:

  1. The initialization (expr1 is evaluated) is done only once at the beginning.
  2. Then the condition (expr2) is tested. If satisfied (evaluates to non-zero) the body of the loop is executed, otherwise the loop is terminated.
  3. When the expr2 evaluates to non-zero the body of the loop is executed. Upon reaching the closing braces of for, control is sent back to for statement, where the increment (expr3) is performed.
  4. Again the condition is tested and will follow the path based on the results of the test condition.
/* Program to print numbers 1 to 10 using for loop */ 
void main(void) 
{ 
   int num; 
   for (num = 1; num <= 10; num++) 
   { 
       printf(“%d \n”, num); 
   } 
}

The features of the for loop

One or more variables can be initialized (expr1) at a time in for loop.

for (p = 0, q = 1; p < 10; p++)

This has two parts in its initialization separated by a comma.

Similar to initialization, the increment section (expr3) may also have more than one part.

for (m = 0, n = 25; m < n; m++, n--)

This has two parts in increment section, m++ and n–, separated by a comma.

The test condition (expr2) may have any compound relation and testing need not be limited only to loop control variable.

for (i = 1, sum = 0; i < 10 && sum < 50; i++ )

This loop uses the compound test condition with loop control variable i and sum.

Any of the three parts can be omitted, although the semi colon must remain.

for ( ; p < 100; )

Both initialization (expr1) and increment (expr3) sections are omitted. If the test condition (expr2), is not present, it is taken as permanently true, so

for ( ; ; ) { 
   statement-block; 
}

is an “infinite” loop, presumably to be broken by other means, such as a break or return.

Loop Interruption

It is sometimes convenient to be able to exit from a loop other than by testing the loop termination condition at the top or bottom.

The break statement

The break statement provides an early exit from for, while, and do, just as from switch. A break causes the innermost enclosing loop or switch to be exited immediately.

/* Program to print sum of prime numbers between 10 and 100 */ 
void main(void) 
{ 
    int sum = 0, i, j; 
    for (i = 10; i <= 100; i++) 
    { 
       for (j = 2; j  sqrt(i)) 
          if (i % j = = 0)
             break;

       if (j > sqrt(i))   
          sum += i; 
    } 
    printf (“%d \n”, sum); 
}

The break statement breaks the inner loop as soon as the first divisor is found, but the iteration continues in the outer loop for the next value of i.

The continue statement

The continue statement is used to bypass the remainder of the current pass through a loop.That is, it passes the flow of control to the next iteration within for, while or do loops.

In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch.

for (i = 0; i < n; i++) 
{ 
   if (arr[i] < 0) 
      continue; 
   sum += a[i]; 
}

The above code fragment calculates the sum of only the positive elements in the array arr; negative values are skipped.

The exit function

The standard library function, exit ( ), is used to terminate execution of the program. The difference between break statement and exit function is, break just terminates the execution of loop in which it appears, whereas exit ( ) terminates the execution of the program itself.

Related Post