Jumps and countdowns
Make a loop skip ahead by more than one, or count backwards. About 8 minutes.
Jumping ahead
A loop doesn't have to go up by one. Think of climbing a staircase two steps at a time, or reading every fifth page of a book.
A range can take a third number, the size of each jump. In Python, range(2, 11, 3) starts at 2 and adds 3 each time, so it gives 2, 5 and 8. The next would be 11, which is past the end. The other languages write this inside the for line, as the part that says what happens after each pass.
for i in range(2, 11, 3):
... # i is 2, then 5, then 8- i
- 4
- total
- 4
The loop starts at 4 and jumps by 4 each pass. The first i is 4, and the total is 4.
Counting down
Give the range a negative jump, and the counter walks backwards. A rocket countdown goes 10, 9, 8 and all the way to 1.
When you count down, the start is the big number and the stop is the small one. And as always, the stop number itself is left out, so to reach 1, stop at 0. You can also jump by more than one while counting down, such as counting down by 2.
for i in range(10, 0, -2):
... # 10, 8, 6, 4, 2Which values does range(1, 10, 3) take?
- A1, 4 and 7
- B1, 4, 7 and 10
- C3, 6 and 9
Show the answer
1, 4 and 7. Start at 1 and add 3 each time: 1, 4, 7. The next would be 10, but the end value is not included.
Every k-th number
Return the sum of every k-th number from k up to n: k, 2k, 3k and so on, as long as they don't go past n. The sum can be large, so the result is a long.
n = 12, k = 4 → 24
0 ≤ n ≤ 1,000,000 · 1 ≤ k ≤ 1,000,000