While Loops
A while
loop in C++ repeatedly executes a block of code as long as a given condition remains true.
The condition is evaluated before each iteration, making it ideal for scenarios where the number of repetitions is not known in advance.
Use while
loops when you want to continue looping until some runtime condition changes, such as reading input until end-of-file or waiting for a user action.
Syntax
while (condition) {
// loop body
}
- condition: a boolean expression checked before each pass
- loop body: code block that runs only if the condition evaluates to true
For example, to count from 1 to 5:
#include <iostream>
using namespace std;
int main(void){
int count = 1;
while (count <= 5){
cout << i << " ";
count++;
}
cout << endl;
}
Prints this line:
.github/scripts/run_all_cpp.sh: line 23: ./project.out: No such file or directory
Iterating over an Array
int values[4] = {10, 20, 30, 40};
int i = 0;
while (i < 4) {
cout << values[i] << endl;
i++;
}
Here, the loop variable i
is declared outside the loop, and incremented within the body.
Infinite Loops
A while
loop whose condition never becomes false runs indefinitely:
while (true) { // infinite loop }
Ensure you include a break
or altering condition when an infinite loop must terminate.
Pros and Cons
- Advantages
- Flexibility: Loop continues based on runtime conditions
- Simplicity: Clear structure for conditional repetition
- Disadvantages
- Risk of infinite loops if condition never becomes false
- Less concise when loop control variables require manual setup
Reading Questions
- What is the key difference between a
while
loop and afor
loop in C++? - Write a
while
loop that prints the numbers from 10 down to 1. - In a
while
loop, when is the condition checked relative to the loop body execution? - How can you prevent an infinite
while
loop from running forever? - What do break and continue do inside a
while
loop? - Given an array
int data[5]
, write awhile
loop to compute the sum of its elements. - Where must you declare the loop control variable if you want to use it after the loop ends?
- Describe a use case where a
while
loop is more appropriate than afor
loop.