Loops -- For statement:
The third and last looping construct in C is the for loop. The for loop can execute a block of code for a fixed or given number of times. Its syntax is as follows. The basic format of the for statement is:
for ( start condition; continue condition; re-evaluation)
program statement;
for ( expr 1; expr 2; expr 3; )
statement
is equivalent to
expr 1;
while ( expr2 )
{
statement
expr 3;
}
The simplest way to understand for loops is to study several examples.
First, here is a for loop that counts from 1 to 10.
for (count = 1; count <= 10; count++)
{
printf("%d\n",count);
}
The test conditions may be unrelated to the variables being initialized and updated. Here is a loop that counts until a user response terminates the loop.
for (count = 1; response != 'N'; count++)
{
printf("%d\n",count);
printf("Dam man, you still want to continue? (Y/N): \n");
scanf("%c",&response);
}
An example of using a for loop to print out characters
#include <stdio.h>
int main(void)
{
char letter;
for (letter = ‘A’; letter <= ‘E’; letter = letter + 1)
{
printf(“%c”, letter);
}
return 0;
}
Example program:
#include <stdio.h>
int main(void)
{
int count;
for (count = 1; count <=10; count = count + 1)
printf(“%d”, count);
printf(”\n”);
return 0;
}
Sample program output
1 2 3 4 5 6 7 8 9 10
Example program 2:
1. For loop sample