for loop

The for loop statement is usually used to execute a single line of statement or block of statement for a specified number of times.

The syntax is:-

for ( initialization; condition; increment/decrement )
{

statement 1;
statement 2;
statement 3;
………………
statement n;

}

Inside for() loop, the first expression is used to initialize the variable , second expression is used to check condition true or false, and third statement is used to increment/decrement the variable.

Remeber in while loop, we do initializtion, condition check and increment at three different places, here all three things has come at one place. Lets see one example.

Write a program to print 0 to 10 numbers on display.

#include<stdio.h>
int main()
{

int count;for (count = 0; count <= 10; count++)

{

printf(“%d \t”,count);

}
return 0;

}

Now we will see how compiler execute above C program :-
Inside for () loop the first expression initializing value of count to 0.  This is the expression which is execute only one time, after executing first expression compiler moves to second expression where we check condition true or false if condition is true the statmemnt(s) inside for loop braces will execute and again compiler moves to third expression,  here value of count increment by one. Again compiler moves to second statement and checks condition, if conditions is true the statmemnt(s) inside for loop braces will execute and again compiler moves to third expression, likewise compiler increment value of count and checks condition until condition becomes false.  Whenever expression evaluate as false compiler comes out from the loop and execute next line after loop. The output of above C program is :-
$  ./a.out
0    1    2    3    4    5    6    7    8    9    10

Now write a program to print 5 to 10 numbers on display.  think what to do, Just initialize variable equal to 5 in first expression of  for() loop, see below.

#include<stdio.h>
int main()
{

int count;for (count = 5; count <= 10; count++)
{

printf(“%d \t”,count);

}
return 0;

}

The output is :-
$  ./a.out
5    6    7    8    9    10

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.