C++ do-while loop
The do while loop
Sometimes, there is need to execute a block of statements first then to check condition. At that time such type of a loop is used. In this, block of statements are executed first and then condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}while(condition);
In above syntax, the first the block of statements are executed. At the end of loop, while statement is executed. If the resultant condition is true then program control goes to evaluate the body of a loop once again. This process continues till condition becomes true. When it becomes false, then the loop terminates.
Simple Example :
#include <iostream.h>
#include <conio.h>
void main()
{
int a;
clrscr();
a=1;
do
{
cout << "\nHello";
a = a + 1
}while(a<=5);
a=6;
do
{
cout << "\n\nHi"; // 1 time
a = a + 1
}while(a<=5);
getch();
}
Output:
Hello
Hello
Hello
Hello
Hello
Hi
Description :
First the value of a is set to 1. Since it is do while loop, the do part will execute atleast one time.
Hence 'Hello' is printed and in the next statement the value of a is incremented and becomes 2. Now the while condition is checked which is true since 2 <=5 hence again the control goes to the do loop and print 'Hello' and the value of a is again increased which becomes 3. Similarly the process continous till the condition become false.
When the condition become false the control goes to the next statement in which value of a is changed to 6 and the next statement is second do while loop. Since it is do while, it print 'Hi',in the next statement the value is incremented and becomes 7. Next the while condition is checked which comes out to be false and hence the control terminates from the do while loop.
Note :
We will discuss more programs in our C++ programs section.
Labels:
C++ do-while loop,
do while c++,
do- while loop
Subscribe to:
Post Comments (Atom)
1 comments:
Great blog! The information you provide is quiet helpful, why I was not able to find it earlier.
C, c++ training chandigarh
Post a Comment