Do-While Loop
A while loop checks its condition before the first round. If the condition is false from the start, the body never runs. A do-while loop does it the other way around: it runs the body first, and checks the condition after. So the body always runs at least once.
Here both loops get the same false condition:
#include <iostream>
using namespace std;
int main() {
int n = 0;
while (n > 0) {
cout << "while body ran" << "\n";
}
do {
cout << "do-while body ran" << "\n";
} while (n > 0);
return 0;
}
Output:
do-while body ran
n > 0 is false. The while loop checked it first and skipped its body. The do-while loop ran its body once, then checked the condition and stopped.
Look at the shape of a do-while. The word do comes first, then the body, then while with the condition. The line ends with a semicolon after the closing parenthesis. A normal while loop has no semicolon there, so this one is easy to forget.
When to use do-while
Use do-while when you must do something once before you can check anything. A good example is asking for input. You cannot check a PIN before you have read it:
int pin;
do {
cout << "Enter your PIN" << "\n";
cin >> pin;
} while (pin != 4321);
cout << "Welcome" << "\n";
Output:
Enter your PIN
Enter your PIN
Welcome
The input was 1111 and then 4321. (Input does not appear in the output, only what the program prints.) In the first round, the program read 1111. That is not the right PIN, so pin != 4321 was true and the loop ran again. In the second round, it read 4321. Now the condition was false, and the loop ended.
With a normal while loop, you would have to read the PIN once before the loop and once more inside it. The do-while lets you write the reading code only once.
In most other cases, a while loop is the better choice. Use do-while only when the body must run before the condition makes sense.
In the exercise, keep reading numbers until you read a 0, and add them up with a do-while loop.