Why loops?
Imagine printing the numbers 1 to 100. Writing 100 cout lines would be silly. A loop repeats a block of code for you.
while
A while loop keeps repeating its block as long as its condition is true:
#include <iostream>
using namespace std;
int main() {
int count = 1;
while (count <= 5) {
cout << "Count: " << count << "\n";
count++;
}
cout << "Done!\n";
return 0;
}Output
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5 Done!
Step by step:
countstarts at 1. Is1 <= 5? Yes, so the block runs: it prints and adds 1.- Back to the top: is
2 <= 5? Yes... and so on. - When
countbecomes 6,6 <= 5is false, so the loop stops and the program moves on.
Think of it like this: A while loop is like eating from a bowl of chips: while there are chips left, take one. When the bowl is empty, you stop.
Common mistake: Forgetting to change the loop variable. Without
count++,countstays 1 forever and the loop never ends. This is called an infinite loop.
Adding things up
Loops are often used to build up a total:
#include <iostream>
using namespace std;
int main() {
int number = 1;
int total = 0;
while (number <= 100) {
total += number;
number++;
}
cout << "1 + 2 + ... + 100 = " << total << "\n";
return 0;
}Output
1 + 2 + ... + 100 = 5050
Reading until a stop value
A while loop is perfect when you don't know in advance how many times to repeat. Here we read numbers until the user types 0:
#include <iostream>
using namespace std;
int main() {
int n;
int sum = 0;
cin >> n;
while (n != 0) {
sum += n;
cin >> n;
}
cout << "Sum: " << sum << "\n";
return 0;
}Input (what the user types)
4 10 6 0
Output
Sum: 20