C++ 13: Do While Loop
The do...while loop is a variant of the while loop with one important difference: the body of do...while loop is executed once before the condition is checked.
Its syntax is:
do {
// body of loop;
}
while (condition);Here,
- The body of the loop is executed at first. Then the
conditionis evaluated. - If the
conditionevaluates totrue, the body of the loop inside thedostatement is executed again. - The
conditionis evaluated once again. - If the
conditionevaluates totrue, the body of the loop inside thedostatement is executed again. - This process continues until the
conditionevaluates tofalse. Then the loop stops.
Program:
#include <iostream>using namespace std;
main(){ int e_s = 0, o_s = 0; int i;
do { /* code */ cout << "Enter a number:"; cin >> i; if (i % 2 == 0) { e_s = e_s + i; } else { o_s = o_s + i; }
} while (i > 0);
cout << " even numbers sum is :" << e_s << endl; cout << "odd Numbers sum is :" << o_s << endl;}Output:
Enter a number:34
Enter a number:3
Enter a number:3
Enter a number:4
Enter a number:-1
even numbers sum is :38
odd Numbers sum is :5
Comments
Post a Comment