Loop statement is used to iterate a block of statement. Generally a loop statement has three parts.
1. Loop initialization.
2. Loop condition.
3. Loop increment or decrement.
Loop statement first stores initial value in loop control variable and then check condition with loop control variable for taking decision and then increases or decreases the initial value. Mainly three types of loop statements are used in C and C++ programming.
2. Loop condition.
3. Loop increment or decrement.
Loop statement first stores initial value in loop control variable and then check condition with loop control variable for taking decision and then increases or decreases the initial value. Mainly three types of loop statements are used in C and C++ programming.
1. for loop statement
2. while loop statement
3. do while loop statement
3. do while loop statement
for Loop Statement
for loop statement is the mostly used loop statement in C and C++ programming. The basic structure of a for loop statement is shown below.
for (initialization ; condition ; increment/decrement )
{
loop body;
}
Say, you want to print numbers from 1 to 100. For this, you can use a for loop statement. An example is given below.
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr ();
for(int counter =1; counter<=100; counter++)
for(int counter =1; counter<=100; counter++)
{
printf (“%d\t”, counter);
}
getch();
}
Program Output
Program Output
while Loop Statement
while loop statement works same as for loop statement. The structure of a while loop statement is given below.
initialization;
while (condition)
{
loop body;
increment/decrement;
}
Say, you want to print those numbers which are divisible by 5 from 1 to 100. For this, you can use a while loop statement. An example is given below.
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr ();
int counter = 5;
while (counter<=100)
{
printf (“%d\t”,counter);
counter = counter+5;
}
getch();
}
Program Output
Program Output
do while Loop Statement
do while loop statement works same as while loop statement but only difference is that do while loop statement checks condition after executing first block and while loop statement first checks condition and then executes any block. The above example can be done with do while loop statement. The above example with do while statement is given below.
#include<stdio.h>
#include<conio.h>
void main ()
{
clrscr ();
int counter = 5;
do
{
printf (“%d\t”,counter);
counter = counter+5;
}while (counter<=100);
getch();
}This example will generate same output like above example but the structure and working procedure is different.