C++ While Loop
The while loop in C++ executes a block of code repeatedly as long as a given condition evaluates to true. It is useful when the number of iterations is not known beforehand.
1. Basic While Loop Example
This example prints numbers from 1 to 5 using a while loop.
C++
Example: Basic while loop
#include <iostream>
using namespace std;
int main() {
int i = 1;
while(i <= 5) {
cout << i << endl;
i++;
}
return 0;
}
2. Common Mistakes
A common mistake is forgetting to update the loop variable, which can result in an infinite loop. Always ensure the condition will eventually become false.
C++
Incorrect while loop example
#include <iostream>
using namespace std;
int main() {
int i = 1;
while(i <= 5) {
cout << i << endl;
// i++ is missing, causing an infinite loop
}
return 0;
}
Conclusion
C++ while loops are useful for executing code repetitively when the number of iterations is unknown. Proper loop control ensures efficient and correct execution.
Codecrown