Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Do...while Loop | Introduction to Program Flow
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Variables and Data Types
3. Introduction to Operators
4. Introduction to Program Flow
5. Introduction to Functions

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:

cpp

main

1234567891011121314
#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:

cpp

main

123456789101112131415161718
#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?

Section 4. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt