For loop syntax in C

for(<loop variable initialization>;<loop condition>;<loop variable increment/decrement>)
{
           loop statement 1;
           loop statement 2;
           loop statement 3;
              ………………….
           loop statement N;
}


Example:
#include<stdio.h>
#include<conio.h>
 
void main()
{
 
     int i;
     clrscr();
 
     for(i=1;i<=10;i++)
     {
            printf("%d for loop.\n",i);
     }
      getch();
}
When above “for loop” block (line no. 10 - 13) gets executed let me tell you what happens.

For loop execution steps:

  • At first value of “i” is set to 1, this happens only once in loop execution.
  • Next loop condition (i<=10) is tested. Since value of “i” is 1, it satisfies loop condition and loop statement is executed.
  • When we reach at closing brace of “for loop” then control moves back to beginning of “for loop” and where value of “i” is incremented by 1 (i++).
  • Again it starts from step no. 2. This looping will continue till loop condition (i<=10) is tested to false (means condition is no longer true because value of “i” would be greater than 10, i.e. 11).
  • When value of “i” reaches to 11 then control exits from loop and next statement, after loop block, is executed (in above program line no. 14).

No comments:

Post a Comment