cint university / 101 / ced, the cint editor
101-07: counting loops
This is lesson 101-07 of CU-101.2, checked against cint 0.2.0.
You will repeat lines a set number of times, put one loop inside another and line up numbers in rows.
the program
// Times tables from 1 to 9.
for row in 1..=9 {
for col in 1..=9 {
"{row * col:>3}";
}
"\n";
}
Run it:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
what happened
A for loop counts. Lesson 101-05 met the loop: for row in 1..=9 { ... } runs the lines between the braces once for each number from 1 to 9, and row holds that number. Each time through the lines is called a pass.
A range says where to start and stop. There are two ways to write one:
1..=9means 1 up to 9, including 9.1..9means 1 up to 9, leaving 9 out: 1 to 8.
The second kind is useful when counting starts at 0, as it does for lists in lesson 101-12. 0..7 gives seven numbers, 0 to 6.
A loop can hold another loop. For each row, the inner loop runs through col from 1 to 9. The line "{row * col:>3}"; runs 9 times 9, which is 81 times, once for each number in the table.
A print without \n stays on the same line. The inner loop prints nine numbers side by side. After it ends, "\n"; ends the line, and the outer loop goes on to the next row.
:>3 sets a width. {row * col:>3} prints the number in 3 characters, with spaces in front to fill them, so 4 prints as two spaces and a 4. This keeps the numbers lined up under each other. The > means the number goes at the right of its space.
change it
- Change
1..=9to1..9in both loops. Which row disappears, and which number disappears from each row? - Make the table go up to 12 in both loops. Look at the last rows: what goes wrong, and what width fixes it?
- Print only the squares, 1, 4, 9 and so on up to 81, one on each line. You need only one loop.
the last rows of the 12 table
9 18 27 36 45 54 63 72 81 90 99108
10 20 30 40 50 60 70 80 90100110120
11 22 33 44 55 66 77 88 99110121132
12 24 36 48 60 72 84 96108120132144
From row 9 on, numbers with three digits fill all 3 characters and run together. A width of 4 leaves a space between them.
when it goes wrong
A for loop's counter belongs to the loop, and the lines inside cannot change it:
for row in 1..=3 {
row = 5;
}
error[C2052]: loop variable assigned
--> loopvar.ci:2:5
|
2 | row = 5;
| ^
|
A range also counts only upward. This loop never runs its lines, because 10 is past 1, so the program prints only done:
for i in 10..1 {
"{i}\n";
}
"done\n";
Lesson 101-08 shows a loop that can count down.