for loop is used where the loop will be traversed a fixed number of times.
for (expression1; expression2; expression3)
{
block of statements;
}
1) expression1 : this allows you to initialise a variable.
2) expression2 : this gives the condition to loop.If it suppose to true then body of loop containing multiple statements will execute otherwise loop terminated.
3) expression3 :It increment or decrement the variable initialises in expression1 by using operators like (++ and –).
Example:
#include<stdio.h>int x;
main()
{
for (x=3;x>0;x–)
{
printf(”x=%d\n”,x);
}
}Output:
x=3
x=2
x=1
while loop
while ( condition )
{
Code to execute while the condition is true
}
As much as the condition is true the statements written in curly braces executes else loop terminates and compiler comes out from loop.It is somewhat similar to if statement but the only difference is while loop continue running till condition will not be false.
Example :
main()
{
int x=1;
while (x>2);
{
printf(”x=%d\n”,x);
x–;
}
}
do while loop
do
{
statement;
}
while (expression);
do while loop is as that of while .The only difference is do while checks the condition after showing the result. Thus during first compilation through loop although the condition is false it shows output then terminated on the other hand while loop termited from beginning if this situation occurs.
Example :
main()
{
int x=1;
do
{
printf(”x=%d\n”,x);
x–;
}
while (x>2);
}
Output:
x=1
