for (initialization; comparison; increment)
single_statement;
for (initialization; comparison; increment)
{
statement(s);
}
for (i = 2; i <= 6; i++)
printf("%d ",i);
OUTPUT: 2 3 4 5 6
start = 3;
finish = 7;
step = 2;
for (i = start; i < finish; i = i + step)
printf("%d ", i);
OUTPUT: 3 5
start = 7;
finish = 3;
step = 2;
for (i = start; i > finish; i = i - step)
printf("%d ", i);
OUTPUT: 7 5
C does NOT restrict the for loop to being simply a counter control. It allows the for loop to do everything that a while or do-while loop can. However, you should ONLY use the for loop for counter controlled loops and the while or do-while for logic control. Following are some examples of the poor use of for loops.
for (count = 0, temp = 2; ((count < 10)&&(temp > 0));
count += 3, temp--)
printf("%d %d \n", count, temp);
OUTPUT: 0 2
3 1
Equivalent while
count = 0;
temp = 2;
while ((count < 10)&&(temp > 0))
{
printf("%d %d \n", count, temp);
count += 3;
temp--;
}
count = 3;
for (temp = 2; ((count < 10)&&(temp > 0)); count += 3, temp--)
printf("%d %d \n", count, temp);
OUTPUT: 3 2
6 1
Equivalent while
count = 3;
temp = 2;
while ((count < 10)&&(temp > 0))
{
printf("%d %d \n", count, temp);
count += 3;
temp--;
}
for (count = 0; count < 5; printf("%d ", count++));
OUTPUT: 0 1 2 3 4
Equivalent while
count = 0;
while (count < 5)
{
printf("%d ", count);
count++;
}
for (count = 0; count < 4; )
{
printf("%d ", count);
count = count + 1;
}
OUTPUT: 0 1 2 3
Equivalent while
count = 0;
while (count < 4 )
{
printf("%d ", count);
count = count + 1;
}
count = 0;
for (; count <= 10; )
{
printf("%d ", count);
count = count + 2;
}
OUTPUT: 0 2 4 6 8 10
Equivalent while
count = 0;
while (count <= 10)
{
printf("%d ", count);
count = count + 2;
}