While Loop
The while Loop in C++:
The while loop in C++ is used to repeatedly execute a block of code as long as a specified condition is true. The syntax of a while loop is as follows:
while (condition) {
// Code to be executed as long as the condition is true
}
Here's a simple example of a while loop that prints the numbers from 1 to 5:
#include <iostream>
int main() {
int i = 1;
while (i <= 5) {
std::cout << i << " ";
++i; // Increment the loop control variable
}
return 0;
}
In this example:
int i = 1initializes the loop control variable.i <= 5is the condition that is checked before each iteration.++iincrements the loop control variable, ensuring that the loop will eventually terminate.
The output of this program will be:
1 2 3 4 5
It's important to ensure that the loop control variable is modified within the loop body so that the condition can eventually become false, leading to the loop's termination. Failure to do so may result in an infinite loop.
You can use the break statement to exit the while loop prematurely, and the continue statement to skip the rest of the loop body and move to the next iteration.
#include <iostream>
int main() {
int i = 1;
while (i <= 10) {
if (i % 2 == 0) {
++i; // Increment only for even numbers
continue;
}
std::cout << i << " ";
if (i == 5) {
break; // Exit the loop when i is 5
}
++i;
}
return 0;
}
In this example, the loop prints odd numbers from 1 to 9 and exits when i becomes 5.