Header Ads Widget

for Loop in C

for(Initialization ; Test expression ; Update expression ) 
{

body of loop
.....................

}

It has three expressions : initialization, test expression and update expression and semicolons are used for separating these expressions. 
Initialization is executed only once when the loop starts and is used to set the loop control variable . This expression is generally an assignment expression. Test expression is a condition ( relational expression)  that is tested before each iteration of the loop. When Test expression is true then statements  written as body of loop are  executed . Update expression is executed each time after body of loop is executed and updates the value of loop control variable . This process continues till the condition is true . When the condition becomes false the loop is terminated and control is transferred to the statement following the loop. 

Example: Program in C to print numbers from 1 to 10.

#include<stdio.h>
int main()
{
int i;
for(i = 1 ; i<=10 ;i++)
 {
  printf("%d \t ",i);
 }
return 0;
}

we can also write it as :

#include<stdio.h>
int main()
{
int i;
for(i = 0 ; i++<10 ;)
 {
  printf("%d \t ",i);
 }
return 0;
}

The initialization expression can contain more than one one statement separated by comma but only one statement is allowed in test expression. Test expression may contain several conditions linked together using logical operator. Multiple statements can also be used in update expression.

Post a Comment

0 Comments