×
☰ Menu

for Loop

 

This loop is used when we have to execute a part of code in finite times.

Syntax of for loop:

for (Expression 1; Expression 2; Expression 3)
{
Loop body
}


Expression 1: Setting a loop counter to an initial value.
Expression 2: Testing the loop counter to determine whether its value has reached the number of repetitions desired.
Expression 3:(‘loop counter or index variable) Increasing the value of loop counter each time the program segment within the loop has been executed. 


Flow Chart of for loop: same as while loop

Sample program on for loop

#include<stdio.h>
#include<conio.h>
int main( )
{
int p, n, count ;
float r, si ;
for(count = 1 ;count <= 3;count++)
{
printf ( "Enter values of p, n, and r: \n" ) ;
scanf ( "%d %d %f", &p, &n, &r ) ;
si = p * n * r / 100 ;
printf ( "Simple Interest = Rs.%f\n", si ) ;
}
getch();
return 0;
}

 

Output:

Enter values of p, n, and r:
500
6
6
Simple Interest = Rs.180.000000

 

Let us now examine how the for statement gets executed:

  • When the for statement is executed for the first time, the value of count is set to an initial value 1.
  • Now the condition count <= 3 is tested. Since count is 1 the condition is satisfied and the body of the loop is executed for the first time.
  • Upon reaching the closing brace of for, control is sent back to the for statement, where the value of count gets incremented by 1.
  • Again the test is performed to check whether the new value of count exceeds 3.
  • If the value of count is still within the range 1 to 3, the statements within the braces of for are executed again.
  • The body of the for loop continues to get executed till count doesn’t exceed the final value 3.
  • When count reaches the value 4 the control exits from the loop and is transferred to the statement (if any) immediately after the body of for. 

 

 

Nesting of Loops

 

Code: 

#include<stdio.h>
#include<conio.h>
int main ( )
{
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
{
for ( c = 1 ; c <= 3 ; c++ ) /* inner loop */
{
sum = r + c ;
printf ( "r = %d c = %d sum = %d\n", r, c, sum ) ;
}
}
getch();
}




Output: 

r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 1 c = 3 sum = 4
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4
r = 2 c = 3 sum = 5
r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5
r = 3 c = 3 sum = 6

 

 

Note:  for loop can occur within a while loop, or a while within a for loop.