Lesson 4
Loops
Short answer: a loop repeats a block until a condition says stop. Use for when you know how many times; use while when you don't.
for: three parts, one line
for (start; condition; step) reads as: set up, test before each pass, move forward after each pass.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "sum = " << sum << endl;
return 0;
}
For n = 5 that is 1+2+3+4+5 = 15. Change n in the input box. This exact shape is Sum from 1 to N.
while: when the count is unknown
Chewing digits off a number is the perfect while: you cannot know in advance how many digits there are.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int digits = 0;
while (n > 0) {
n /= 10; // chop off the last digit
digits++;
}
cout << "digits = " << digits << endl;
return 0;
}
That n /= 10 is integer division doing the chopping — the same rule from lesson 2.
Nested loops: rows and columns
#include <iostream>
using namespace std;
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
cout << "(" << row << "," << col << ") ";
}
cout << endl;
}
return 0;
}
The inner loop finishes completely for each single pass of the outer loop. This is the machine behind Star Pyramid and Multiplication Table.
The three bugs
- Off by one.
i < nvsi <= n. Trace one tiny case by hand (n = 1) before trusting it. - The stray semicolon.
for (...) ;— that;is an empty body; the loop spins and does nothing else. - Infinite loop. If nothing inside moves the condition toward false, it never ends. On this site a runaway loop is killed after 3 seconds, but the habit matters on a real machine.
Practice this lesson
These problems exercise exactly what you just read: