The while loop does not allow body to be executed if test condition is false. The do-while loop is an exit controlled loop and its body is executed at least once.
Syntax of do-while loop:
do
{
statement;
}
while(Condition);
Program 1.1:
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
// do…while loop from 1 to 5
do {
cout << i << ” “;
++i;
}
while (i <= 5);
return 0;
}
Output:
1 2 3 4 5
Program 1.2:
// Program to do the sum of numbers
#include <iostream>
using namespace std;
int main()
{
int num, sum = 0;
cout << “Enter a numbers: “;
do {
cin >> num;
sum += num;
} while (num != 0);
cout << “Sum is ” << sum;
return 0;
}
Output:
Enter a numbers:
2
3
4
0
Sum is 9
Nested do-while loop :
In C++, it is possible for us to create one do-while loop inside another do while loop. This results into a nested do while loop.
Syntax:
do{
statement(s)
do{
statement(s)
}while(condition);
statement(s)
}while(condition);
Program 2.1:
#include <iostream>
using namespace std;
int main()
{ int a = 1;
do
{ int b = 1;
do {
cout << a << “\n”;
b++;
} while (b <= 2);
a++;
} while (a <= 2);
}
Output :
1
1
2
2
Pingback: While Loop in C++ - AskAtul.com
Pingback: Unconditional control statement in C++ - AskAtul.com