The for loop
The ‘for loop’ is used as a counter-controlled loop, as we can accurately predict the number of iterations.
A ‘for loop’ is a pre-test loop that includes three expressions in its header:
- Loop initialization statement
- Limit test expression
- Loop update statement
‘C’ program allows to updating the loop control statement from within the loop body, even though it is not recommended.
All loops in C program execute as long as a condition is evaluated as true and terminate when the condition is evaluated as false.
Example:
/* Print number series from 1 to user specified limit. */
#include<stdio.h>
int main(void)
{
//local declarations
int limit;
//statement
printf("\Enter the limit:");
scanf("%d",&limit);
printf("\n");
for(int i=1; i<=limit; i++)
printf("%d"\n", i);
return 0;
} //main
OUTPUT:
Enter the limit: 3
1
2
3