do while loop c++
Do-while loop in C++ is a type of loop that executes a block of code at least once, and then repeats as long as a specified condition is true. The basic structure of a do-while loop is as follows:
do {
// code to be executed
} while (condition);
In this structure:
- The code inside the do
block is executed first.
- Then, the condition inside the while
is evaluated.
- If the condition is true, the code inside the do
block is executed again.
- This process continues until the condition becomes false.
Here's an example of a simple do-while loop in C++ that prints numbers from 1 to 5:
#include <iostream>
int main() {
int i = 1;
do {
std::cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
In this example:
- We initialize the variable i
with a value of 1.
- Inside the do
block, we print the value of i
followed by a space and then increment i
by 1.
- The condition in the while
statement checks if i
is less than or equal to 5. If it is true, the loop continues; otherwise, it terminates.
Output:
1 2 3 4 5