0

C for Loop


The for loop is used when the number of time the loop repeated is specified. The format of the for loop is:

for (initialization; condition; increment) {
  statements;
}

The following steps show how the for loop is executed:

  1. Initialize variable, the value usually is 0
  2. Check the condition
  3. If the condition is true, statements are executed
  4. The value of the variable increased by 1
  5. Loop from #2 to #4 until the condition becomes false

Here is the sample code for the for loop:

/*
 *
 * for.c
 *
 * Program to demonstrate the use of the for loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter;
 int total = 0;

 for (counter = 1; counter <= 100; counter = counter + 1) {
   total = total + counter;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}

Note that the increment of the for loop can also be counter++ instead of counter = counter + 1.

There are no posts related to C for Loop.