Loops: for, while, do-while
Teach the computer to repeat work for you
cout five times, you write it once inside a loop and tell the loop how many times to repeat.
- write a for, a while, and a do-while loop,
- choose the right loop for the job,
- control a loop with break and continue.
1. What is a loop?
Imagine you are told: "Do ten push-ups." You do not get ten separate instructions. You get one instruction plus a rule: repeat until you reach ten. That is exactly what a loop is - one block of code plus a rule that says how long to keep repeating.
Every loop needs three things to be safe: a start (where do we begin?), a condition (should we keep going?), and a change (something that moves us toward stopping). If the change is missing, the condition never becomes false and the loop runs forever - an infinite loop.
2. The for loop - when you know the count
A for loop packs all three parts onto one line: for (start; condition; change). Use it when you know how many times to repeat.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << endl;
return 0;
}
Output:
1 2 3 4 5
Read the header for (int i = 1; i <= 5; i++) as three steps:
- int i = 1 - the start: create a counter and set it to 1 (runs once).
- i <= 5 - the condition: keep looping while this is true.
- i++ - the change: add 1 to
iafter each pass.