While Loops — Repeat Until Done
Keep repeating as long as the condition is true
Open interactive version (quiz + challenge)Real-world analogy
Imagine you have a bowl of candy. You keep eating one piece WHILE the bowl is not empty. The moment the bowl is empty, you stop. That is exactly how a while loop works — it keeps running the code inside it as long as the condition stays true.
What is it?
A while loop is a control structure that repeats a block of code as long as a given condition remains true. Before each repetition, C++ checks the condition. If true, it runs the body. If false, it skips past the loop and continues with the rest of the program.
Real-world relevance
While loops are everywhere in competitive programming. Reading input until end-of-file, searching for a value, simulating a process step by step, or repeatedly halving a number (like in binary search) all use while loops. They are your go-to tool when you do not know in advance how many times you need to repeat.
Key points
- The While Loop Syntax — A while loop looks like: while(condition) { body }. First C++ checks the condition. If it is true, it runs the body. Then it checks again. This repeats until the condition becomes false.
- Counting with While — You can count from 1 to N using a while loop: set i = 1, then while(i <= N), print i, then do i++. Each time through the loop, i grows by 1 until it passes N.
- Summing Numbers — To add numbers from 1 to N: start sum = 0 and i = 1. While i <= N, do sum += i and i++. When the loop ends, sum holds the total. For N = 5, you get 1+2+3+4+5 = 15.
- The Danger of Infinite Loops — If you forget to change the variable that the condition checks, the condition stays true forever and your program never stops. This is called an infinite loop. Always make sure something inside the loop moves you toward the condition becoming false.
- Break — Emergency Exit — The break statement immediately exits the loop, no matter what the condition says. It is like an emergency stop button. Use it when you find what you need and want to stop looping early.
- Continue — Skip This Round — The continue statement skips the rest of the current iteration and jumps back to the condition check. It is like saying 'skip this one, move to the next'. Useful for ignoring certain values.
- While vs If — An if statement checks a condition once. A while loop checks the same condition over and over. If you need to repeat something, use while. If you only need to decide once, use if.
- Reading Until a Special Value — A common CP pattern: read numbers until the user enters 0 or -1. Use while(true) with cin >> x, and break when x equals the sentinel value. This lets you process an unknown number of inputs.
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
// Count from 1 to 5
int i = 1;
while (i <= 5) {
cout << i << " ";
i++;
}
cout << endl;
// Output: 1 2 3 4 5
// Sum from 1 to 10
int sum = 0;
int j = 1;
while (j <= 10) {
sum += j;
j++;
}
cout << "Sum = " << sum << endl;
// Output: Sum = 55
// Read numbers until 0, print their sum
int x, total = 0;
cout << "Enter numbers (0 to stop): ";
cin >> x;
while (x != 0) {
total += x;
cin >> x;
}
cout << "Total = " << total << endl;
return 0;
}Line-by-line walkthrough
- 1. We include bits/stdc++.h for all standard tools.
- 2. int i = 1; — We start our counter at 1.
- 3. while (i <= 5) — Before each repetition, check: is i still 5 or less?
- 4. cout << i << " "; — Print the current value of i with a space.
- 5. i++; — Increase i by 1. Without this line, we would loop forever!
- 6. After i becomes 6, the condition i <= 5 is false, so the loop stops.
- 7. For the sum example, sum starts at 0 and we keep adding j to it.
- 8. Each time through the loop, j increases, so we add 1, then 2, then 3... up to 10.
- 9. The sentinel example reads x first, then enters the loop only if x is not 0.
- 10. Inside the loop, we add x to total and read the next x. When x is 0, the loop ends.
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int i = 1;
int sum = 0;
while (i <= 100) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}Need a hint?
The loop condition checks i, but does anything inside the loop actually change i? What will happen when you run this?
Show answer
The bug is that i is never incremented inside the loop! The condition i <= 100 is always true because i stays at 1 forever. This creates an infinite loop. The fix: add i++; inside the while loop body after sum += i;.
Explain like I'm 5
A while loop is like a kid on a trampoline. They keep bouncing WHILE they still have energy. Each bounce is one trip through the loop. When they run out of energy (the condition becomes false), they stop bouncing and climb off.
Fun fact
The first computer bug was literally a real bug — a moth stuck in a relay of the Harvard Mark II computer in 1947. When your while loop runs forever and your program freezes, we still call it a 'bug' even though no insects are involved!
Hands-on challenge
Write a program that reads numbers from input one by one until the user enters -1. Print the count of positive numbers and the count of negative numbers entered (do not count -1 itself). Use a while loop with break.
More resources
- C++ While Loops Explained (YouTube)
- While Loop — cppreference (cppreference.com)
- Loop Practice Problems (Codeforces)