do-while statement in C++

The do-while loop is another repetitive loop used in C++ programs.

When a loop is constructed using the while statement, the test for continuation of the loop is carried out at the beginning of each pass. Sometimes, however, it is desirable to have a loop with the test for continuation at the end of each pass. This can be accomplished by means of do-while statement.

The general form of the do-while statement is

do{
statement 1;
statement 2;
....
....
}
while(expression);

The statement will be executed repeatedly, as long as the value of expression is true (i.e., is non-zero). Notice that statement will always be executed at least once, since the test for repetition does not occur until the end of the first pass through the loop. The statement can be either simple or compound. It must include some feature that eventually alters the value of expression so that the looping action can terminate.

For many application it is more natural to test for continuation of the loop at the beginning rather than at the end of the loop. For this reason, the do-while statement is used less frequently than the while statement.

Program to compute a sum of consecutive integers, i.e., the program to compute the sum 1 + 2 + 3 + .. + n, for an integer input n

#include
void main()
{
int n, i = 0;

cout << "Enter a positive integer: "; cin >> n;

sum = 0;

do{
sum += i++;
}
while(i<=n);

cout << "Sum of first " << n << " integer is " << sum;

}

You may also like...

1 Response

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: