C++ Do-While Loop
The do-while loop in C++ executes a block of code at least once and then continues looping as long as a given condition is true. It is useful when you want the loop body to run at least once regardless of the condition.
1. Basic Do-While Loop Example
This example prints numbers from 1 to 5 using a do-while loop.
C++
Example: Basic do-while loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << endl;
i++;
} while(i <= 5);
return 0;
}
2. Common Mistakes
A common mistake is not updating the loop variable inside the loop, which may lead to an infinite loop. Always ensure the condition will eventually become false.
C++
Incorrect do-while loop example
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << endl;
// i++ is missing, causing an infinite loop
} while(i <= 5);
return 0;
}
Conclusion
C++ do-while loops guarantee that the loop body executes at least once. Proper loop control ensures predictable and correct behavior of repetitive code execution.
Codecrown