Do-While Loop
Do-While Loop
The do-while loop is a control flow structure used in programming languages to execute a block of code repeatedly as long as a specified condition is true. It is called a “post-test loop” because the condition is checked after the code block is executed
The general syntax of a do-while loop is as follows:
do {
// Code block to be executed
} while (condition);
Here’s how the do-while loop works:
- The code block within the
do
section is executed first, without checking the condition. - After executing the code block, the condition is evaluated.
- If the condition is true, the loop continues, and the code block is executed again.
- If the condition is false, the loop terminates, and the program continues with the next statement after the loop.
The key characteristic of a do-while loop is that the code block is guaranteed to execute at least once, regardless of the condition. This makes it useful when you want to perform an action before checking the condition.
C++ Example
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Output
1 2 3 4 5
Java Example
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.print(i + " ");
i++;
} while (i <= 5);
}
}
Output
1 2 3 4 5
Python Example
i = 1
while True:
print(i, end=' ')
i += 1
if i > 5:
break
Output
1 2 3 4 5
JavaScript Example
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Output
1
2
3
4
5