The while
loop is a control structure that allows code to be executed repeatedly as long as a specified condition remains true
. It’s useful when the number of iterations isn’t known in advance and is determined at runtime.
while
while (condition) {
// Code to execute as long as the condition is true
}
condition
: An expression that evaluates to true
(non-zero) or false
(zero).true
, the loop body is executed.false
.while
Loop#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Count is: " << count << endl;
count++;
}
return 0;
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
If the condition never becomes false
, the loop will run indefinitely. For example:
while (true) {
cout << "This will run forever!" << endl;
}
To avoid infinite loops:
break
statement to exit when needed.A while
loop can be used to repeatedly prompt the user for input:
#include <iostream>
using namespace std;
int main() {
int number;
cout << "Enter numbers (enter 0 to stop): ";
cin >> number;
while (number != 0) {
cout << "You entered: " << number << endl;
cin >> number;
}
cout << "Loop ended." << endl;
return 0;
}
5 7 0
You entered: 5
You entered: 7
Loop ended.
The while
loop is often paired with a counter variable to control iterations:
#include <iostream>
using namespace std;
int main() {
int counter = 0;
while (counter < 10) {
cout << counter << " ";
counter++;
}
return 0;
}
0 1 2 3 4 5 6 7 8 9
break
: Exits the loop prematurely.continue
: Skips the rest of the loop body for the current iteration and proceeds to the next iteration.#include <iostream>
using namespace std;
int main() {
int number = 1;
while (number <= 10) {
if (number == 5) {
cout << "Skipping 5" << endl;
number++;
continue;
}
cout << number << " ";
number++;
}
return 0;
}
1 2 3 4 Skipping 5 6 7 8 9 10
while
Loopswhile
loops can be nested to handle multi-dimensional scenarios:
#include <iostream>
using namespace std;
int main() {
int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
cout << "(" << i << ", " << j << ") ";
j++;
}
cout << endl;
i++;
}
return 0;
}
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
while
loops when the number of iterations depends on a condition.