C++ do while loop
In this article, we will learn the usage of do...while
loop in C++ programming. Through various examples, we will gain a better understanding of how these loops work and how they can be utilized in our programs.
Loops are a fundamental component of computer programming, allowing us to repeat a specific block of code multiple times. In C++, there are three types of loops:
for
loop,while
loopdo...while
loop.
Each type of loop has its own unique features and use cases, and in this tutorial, we will focus on the do...while
loop.
The do...while
loop is a control structure in C++ that allows you to repeatedly execute a block of code until a specified condition is met. Unlike the while
loop, the code block within a do...while
loop is executed at least once before the condition is evaluated. The basic syntax of the do...while
loop is as follows:
1do 2{ 3 // code to be executed 4} while (condition);
Here, the code block within the do
statement is executed at least once, and the condition
is evaluated after each iteration of the loop. If the condition is true, the loop continues to execute; if the condition is false, the loop terminates and the program continues with the next statement after the loop.
Let's take a look at two examples of do...while
loops in C++ and their output:
Simple do...while Loop
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int i = 1; 8 do 9 { 10 cout << "Value of i: " << i << endl; 11 i++; 12 } while (i <= 5); 13 14 return 0; 15}
In the above example, the code block within the do
statement is executed at least once, and the condition
is evaluated after each iteration of the loop. The loop continues to execute as long as i
is less than or equal to 5. The value of i
is incremented by 1 after each iteration of the loop. The output will be:
1Value of i: 1 2Value of i: 2 3Value of i: 3 4Value of i: 4 5Value of i: 5
Nested do...while Loop
1#include <iostream> 2 3using namespace std; 4 5int main() 6{ 7 int i = 1; 8 do 9 { 10 int j = 1; 11 do 12 { 13 cout << "Value of i: " << i << " and j: " << j << endl; 14 j++; 15 } while (j <= 2); 16 i++; 17 } while (i <= 3); 18 19 return 0; 20}
In the above example, the outer do...while
loop initializes the value of i
to 1 and continues to execute as long as i
is less than or equal to 3. The inner do...while
loop initializes the value of j
to 1 and continues to execute as long as j
is less than or equal to 2. The output will be:
1Value of i: 1 and j: 1 2Value of i: 1 and j: 2 3Value of i: 2 and j: 1 4Value of i: 2 and j: 2 5Value of i: 3 and j: 1 6Value of i: 3 and j: 2