Looping Statement In C++
Loops in
programming come into use when we need to repeatedly execute a block of
statements.
There
are mainly two types of loops:
1. Entry Controlled loops:
In
this type of loops the test condition is tested before entering the loop body. For
Loop and While Loop are
entry controlled loops.
2. Exit Controlled Loops:
In this type of loops the test condition is
tested or evaluated at the end of loop body. Therefore, the loop body will
execute atleast once, irrespective of whether the test condition is true or
false. do – while loop is exit controlled loop.
Fig: Loop Statement In C++ |
1.
For loop
2.
Do-while loop
3.
While loop
1. For loop
A for loop is a repetition control
structure which allows us to write a loop that is executed a specific number of
times. The loop enables us to perform n number of steps together in one line.
Syntax:
for(initialization;
condition;incr/decr)
{
//statement;
}
Fig: For Loop Statement In C++ |
Program:
#include<iostream.h>
#include<conio.h>
void
main()
{
int
a;
for(a=1;a<=5;a++)
{
cout<<”the
number enter is :”;
}
getch();
}
Output:
The
number enter is: 1
The
number enter is: 2
The
number enter is: 3
The
number enter is: 4
The
number enter is: 5
2.
While loop
In C++,
the loop is used several times for the iteration of a part of the program. If
the iteration number is not set, it is advisable to use the loop rather than
the loop.
Synatx:
While(condition)
{
//statement;
}
Fig: While Statement In C++ |
Program:
#include<iostream.h>
#include<conio.h>
void
main()
{
int
a,b;
cout<<”enter
any no for table”;
cin>>a;
b=1;
while(b<=10)
{
cout<<a*b;
b++;
}
getch();
}
Output:
Enter
any no for table 2
4
6
8
10
12
14
16
18
20
3. Do-while loop
In do
while loops also the loop execution is terminated on the basis of test
condition. The main difference between do while loop and while loop is in do
while loop the condition is tested at the end of loop body, i.e do while loop
is exit controlled whereas the other two loops are entry controlled loops.
Syntax:
do
{
//statement;
}
while(condition);
Fig: Do While Statement in c++ |
Program:
#include<iostream.h>
#include<conio.h>
void
main()
{
int
a,fact;
cout<<”enter
number”;
cin>>a;
fact=1;
do
{
fact=fact*a;
a--;
}
while(a>=1);
cout<<”the
factorial value “<<endl;
getch();
}
Output:
Enter number
4
The factorial value 24
No comments:
Post a Comment