OneBite.Dev - Coding blog in a bite size

Do A While Loop In C++

Code snippet for how to Do A While Loop In C++ with sample and detail explanation

C++ is a powerful high-level programming language that plays a central role in developing various types of software. One of its fundamental concepts is the ‘Do-while’ loop, which is crucial in executing commands based on specific conditions.

Code Snippet: Do-While Loop In C++

Let us dive into a simple example to understand this concept better:

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    do {
        cout << "Iteration " << i << endl;
        i++;
    } while (i <= 5);

    return 0;
}

In this code snippet, the program will print the phrase “Iteration [number]” five times.

Code Explanation: Do-While Loop In C++

The do-while loop is a post-test loop, in other words, the condition is validated after the code within the loop has been executed. The syntax for a do-while loop is as follows:

do {
   // statements
} while (condition);

Let’s break down the previous code snippet for further understanding:

  • int i = 1; : Here, we are declaring an integer variable ‘i’ and initializing it to 1.

  • do { ... } while (i <= 5); : This represents the do-while loop. The code within the braces {} is the code that will be executed in each loop iteration. The condition ‘i <= 5’ following the ‘while’ keyword is checked after the code within the loop is executed.

  • cout << "Iteration " << i << endl; : This line prints “Iteration ” followed by the current value of ‘i’. The ‘endl’ part adds a line break.

  • i++; : This is the increment operator which increases the value of ‘i’ by 1 after each iteration.

  • The loop continues until ‘i’ is greater than 5. After 5 iterations, the condition ‘i <= 5’ becomes false, and the loop ends.

Thus, using the do-while loop in C++, we can execute a block of code repeatedly under a certain condition. Knowing how to use this loop structure can significantly benefit your coding efficiency and capabilities.

c-plus-plus