Problem overview
The task is to print all the odd numbers from 7 through 23, one per line, using a for loop. The output is 7, 9, 11, 13, 15, 17, 19, 21 and 23: nine lines, each two more than the one before.
Approach: change the post statement
The previous printing lessons added 1 on every pass. Here the post statement does the work. If the loop starts at an odd number and adds 2 each time, it only ever lands on odd numbers, so no if is needed to filter anything.
The loop starts at 7, the first number to print. The step is i += 2, which is shorthand for i = i + 2. The end needs a little care: the last value to print is 23, and the loop reaches it exactly, so i <= 23 includes it. The condition i < 24 would behave the same here.
Tracing the loop
Follow the value of i through the passes:
- The loop starts with
iequal to 7. Is7 <= 23? Yes, so 7 is printed, andi += 2makes it 9. - Is
9 <= 23? Yes, so 9 is printed, andibecomes 11. The same happens for 11, 13, 15, 17, 19 and 21. - When
iis 23, the check passes, 23 is printed, andibecomes 25. - Is
25 <= 23? No, so the loop ends after nine passes.
The number of passes is (23 - 7) / 2 + 1, which is 9. Integer division in Go truncates, so for bounds that don't line up exactly, the last value is the last one that still satisfies the condition.
Step by step
- Write the loop with a variable
ithat starts at 7, runs whilei <= 23and grows by 2 on every pass. - Print
iinside the body withfmt.Println, so each value is on its own line.
The solution in Go
for i := 7; i <= 23; i += 2 {
fmt.Println(i)
}
The details:
+=works like it does in other C-style languages.i += 2adds 2 toiin place. It is an assignment statement, so it fits in the post position of the loop header.- The parity never changes. Odd plus 2 is odd, so starting at an odd number keeps every value odd. Starting at 8 would print the even numbers 8, 10, 12 and so on instead.
- The loop checks the condition before each pass. After 23 is printed,
ibecomes 25,25 <= 23is false and the loop ends. The value 25 is never printed.
Edge cases and common mistakes
- Using
i++. That prints every number from 7 to 23, including the even ones. - Starting at the wrong number. Beginning at 6 or 8 produces even numbers all the way through.
- Using
i < 23. The last number, 23, would be missing. - Filtering with
%when it isn't necessary. Looping through every number and checkingi % 2 == 1gives the same output but does twice as many passes. Choosing the right start and step is simpler. The remainder check is the right tool when the numbers don't follow a regular step.
Testing
Run the loop and compare against the nine numbers listed above. As a variation, change the start to 2, the end to 10 and keep the step at 2: the output is 2, 4, 6, 8 and 10.