for Statement in C

The for loop is an entry-controlled loop (like while) in which first the condition is checked, and if it is True then the statements are executed. However, if the condition is False, the control will be transferred to the statement immediately after the body of loop. The condition can be any constant, variable or expression that evaluates to True or False.

The general syntax of for loop requires a counter variable to be initialized within the for statement. Then within the condition, this counter variable needs to be checked against some value. If the condition evaluates to True, the statements within the body of loop will be executed. After this, the control is transferred to counter-modification part of the for loop, from where the control is transferred back to condition. If this time the condition is again True, the body of loop will be executed same way and control will be transferred back to counter-modification and then to the condition. However, if the condition is False, the control will be transferred to the statement immediately following the loop body.

for (counter-initialisation;

condition;
counter-modification;
)
{
statements;
}

One may argue that if we have one entry controlled loop (while) then what for we need another (for)? There are many explanations for existence of for in C language.

1. Some argue that for is faster than while.
2. Most claim that for is used when we know in advance the number of iterations that need to be performed.
3. It is very common that initialization and modification of counter variable is missed by a programmer in while loop. In lieu of this observation, people believe that for-loop is more programmer friendly as compared to while-loop.

We believe first and last argument is acceptable.

It should be noted that if the initialization of counter variable is skipped, then there will be no syntax error but a logical error. Also, if the statement to modify counter variable is skipped, there will be no syntax error. Program 1 shows how to display a multiplication table of any number entered by a user using for loop.

#include <stdio.h>
void main()
{
int number, count, mul;
printf(“Please enter the number? ”);
scanf(“%d”, &number);
for (count = 1; count <= 10; count ++)
{
mul = number * count;
printf(“\n%d x %d = %d”,
number, count, mul);
}
}

Program 1: Program to display multiplication table of a number using for loop.