Course Content
C++ Introduction
C++ Introduction
Do...while Loop
Unlike a while
loop, which may never execute, a do...while loop is guaranteed to execute at least once. Structure of do…while loop:
Note
The line containing the while part ends with a semicolon (
;
)
Now let's compare the while and do…while loops.
The while loop:
main
#include <iostream> int main() { int variable = 0; //loop never executed while (variable == 1) { std::cout << "Hello, I am while loop!" << std::endl; } std::cout << "While loop didn't start :(" << std::endl; }
The do...while loop:
main
#include <iostream> int main() { int variable = 0; do { // this line is guaranteed to be execute at least once std::cout << "Hello, I am Do-Block!" << std::endl; } while (variable == 5); // loop continuation condition std::cout << "Variable doesn`t equal 5, "; std::cout << "so the loop didn't work, "; std::cout << "only the do-block." << std::endl; }
The do...while loop executed one time when the while loop would never have executed.
Everything was clear?