If the while loop is used in situations when the loop may not oven be executed, the do-while is used when the program requires that the loop be executed at least once.
The while loop is a pretest loop, which means is tests its condition before performing an iteration. The do-while loop is a post test loop. This means it performs iteration before testing its condition. As a result, the do-while loop always performs at least one iteration, even if its condition is false to begin with.
do-while loop statement
The general form of the do-while statement is:
do {
statement sequence;
} while (condition);
where:
condition is a relational expression that determines when the loop will exit
statement sequence may either be a single statement or a block of statements that make up the loop body
Unlike the while loop, loop testing in the do-while is done at the bottom of the loop. This allows the statements in between the curly braces to executed first before the condition is tested, so there is at least one iteration for a do-while loop.
Example 1:
/* This program prompts the user to enter terminated when 0 is entered integers which will be and will display the sum of all the integer values entered. */
#include <iostream>
using namespace std;
int a, sum=0;
int main() {
cout<<"\n Enter the series of integers, until is entered \n ”;
sum = 0;
do {
cout<<"\n Enter the number: \n"; cin>> a; sum=sum+a;
} while (a!-0);
cout<<"\n The sum is " << sum;
return 0;
}
SAMPLE OUTPUT
Enter series of integers until 0 is entered:
Enter the number: 27
Enter the number: 12
Enter the number: 0
The sum is 39
Example 2:
/* Write a program that computes the factorial value of n (as input) and displays it. */
#include <iostream>
using namespace std;
int n, f=0, i;
int main () {
cout << "\nEnter a Number\t";
cin >> n;
f = 1;
i = n;
do {
f = f * i;
i--;
} while (i>= 1);
cout<<"\nThe factorial value: "<<f;
return 0;
}
Sample Output:
Enter a Number
5
The factorial value: 120