Iterative statements are used to repeat the execution of a list of statements, depending on the values of an integer expression.
1) While loop 2) Do-While loop 3) for loop.
1) While loop:
Syntax:
While (Test
Expression)
{
Statement block;
}
The while loop
checks whether the test expression is true or not. If it is true, code/s inside
the body of while loop is executed,that is, code/s inside the braces { } are executed.
Then again the test expression is checked whether test expression is true or not. This process continues until the test expression becomes false. When the test expression is false, the while loop is terminated & control goes to the statements just below the while loop.
Example program: sum of n
natural numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();Int
i=0,n=0,sum=0;
cout<<”Eneter
n value\n”;
cin>>n;
while(i<=n)
{
sum=sum+i;
i++;
}
cout<<”sum
of natural numbers are=
“<<sum;
getch();
}
2) Do –While Loop:
The do...while Loop is similar to while loop with one very important difference. In while loop, check expression is checked at first before body of loop but in case of do...while loop, body of
loop is executed first then only test expression is teted. The body of do...while loop is executed at least once.Syntax:
do
{
Statement block;
}
While (Test
Expression);
The statement/s inside body of loop is executed at least once, that is, the statement/s inside braces { } is executed at least once. Then the test expression is checked. If the test expression is true, the body of loop is executed. This process continues until the test expression becomes false.
When the test
expression is false, the do-while loop is terminated & control goes to the
statements just below the do- while loop.
Example program: sum of n natural numbers.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int
i=0,n=0,sum=0;
cout<<"eneter
n value\n";
cin>>n;
do
{
sum=sum+i;
i++;
}
while(i<=n);
cout<<"sum
of natural numbers
are=
"<<sum;
getch();
}
3) For Loop:
For loop has three parts- initialization,condition and increment/decrement
Syntax:
For (initialization; condition; increment/decrement)
{
Statement block
;
}
The initialization statement is executed only once at the beginning of the loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body of for loop is executed and then update expression is updated. This process repeats until test expression is false.
Example program: Find the
Factorial of a given number.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int
fact=1,n=0,i=0;
cout<<"Enter
any number\n";
cin>>n;
if(n==0)
fact=1;
else
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<n<<"
Factorial is= "<<fact;
getch();
}
0 comments:
Post a Comment