C - Statement for Statement


We use the for loop to execute a block of statements for a given number of times.

The general pattern for the for loop is:

for(starting_condition; continuation_condition ; action_per_iteration)


To display the numbers from 1 to 10. Instead of writing ten statements that call printf(), you could write this:

for(int count = 1 ; count <= 10 ; ++count)
  printf("  %d", count);

The first control expression, int count = 1, is executed only once, when the loop starts.

It defines a variable, count, with the initial value 1.

This variable is local to the loop.

The second control expression must be a logical expression resulting in true or false.

The expression count <= 10 will evaluate to true as long as count is not greater than ten.

The second expression is evaluated at the beginning of each loop iteration.

If the expression evaluates to true, the loop continues, and if it's false, the loop ends.

false is a zero value, and any nonzero value is true.

printf() statement is executed as long as count is less than or equal to ten. The loop will end when count reaches 11.

The third control expression, ++count, is executed at the end of each loop iteration.

On the first iteration, count will be 1, so the printf() will output 1.

On the second iteration, count will have been incremented to 2, so the printf() will output the value 2.

You could declare and initialize count to 1 outside the loop:

int count = 1;
for( ; count <= 10 ; ++count)
  printf("  %d", count);


#include <stdio.h>

int main(void)
  int count = 1;// w w w  .  j a  va 2 s . c o  m
  for( ; count <= 10 ; ++count)
    printf("  %d", count);
  printf("\nAfter the loop count has the value %d.\n", count);
  return 0;


Related Topics