for loops in C

The ‘for’  loop is another important looping structure which could replace ‘while’  and ‘do .. while’ loops. It has a special feature that the initialization, test condition and the increment or decrements of test variable could be placed in a single line following the ‘for’ keyword as shown below –

for (initialization; test condition; change of variable){
     statement;
}

Note: 'while' and 'for' loops could be interchanged.

A few examples to illustrate usage of ‘for’ loop –

Example 1:C program to calculate factorial:

main(){
       int n,a=1;
       printf("\nEnter any integer>>");
       scanf("%d",&n);
       
       for(i = n; i >= 1; i--){
          a *= i;
       }
       printf("\nFactorial of %d is %d.", n, a);
}

Example 2:C program to find squares of given n integers:

main(){
       int n,i;
       printf("\nEnter any integer>>");
       scanf("%d",&n);
       
       for(i = 1; i <= n; i++){
          printf("\n%d squared = %d\n", i, i*i);
       }
       
}

Example 3:C program to find sum of numbers until a number:

main(){
       int n,s=0;
       printf("\nEnter any integer>>");
       scanf("%d",&n);
       
       for(i = 1; i <= n; i++){
          s += i;
       }
       printf("\nSum of numbers up-to %d is %d.", n, s);
}