Grade 9 Computer Science — Repeating while something is true
Follow a loop that keeps going while a condition holds, working out what it leaves behind and how many times it went round.
Name: ________________________
1.In each of these a variable is changed as described and the loop keeps going while the variable is below 40. Put them in order of the value the variable is left holding, smallest first.
- Starts at 6 and has 15 added each time
- Starts at 2 and is multiplied by 3 each time
- Starts at 10 and has 9 added each time
- Starts at 1 and is doubled each time
2.This loop doubles a number until the condition stops holding. What does the program print?
n = 1 while n < 20: n = n * 2 print(n)3.In each of these a variable starts at 1 and is multiplied by the number shown every time round, and the loop keeps going while the variable is below 100. Match each multiplier to the value the variable is left holding.
- Multiplied by 2 each time
- Multiplied by 3 each time
- Multiplied by 5 each time
- Multiplied by 10 each time
- Multiplied by 4 each time
- 256
- 128
- 125
- 100
- 243
4.Look at the condition before you follow anything. What does this program print?
n = 5 while n > 10: n = n + 1 print(n)- a) 5
- b) 10
- c) 6
- d) 11
5.This one comes down rather than up. What does the program print?
n = 100 steps = 0 while n > 1: n = n - 30 steps = steps + 1 print(steps)6.This loop is left holding a value the condition would not have allowed it to start from. What does the program print?
n = 64 steps = 0 while n > 5: n = n - 12 steps = steps + 1 print(n)7.Both variables change every time round here, and only one of them is in the condition. What does the program print?
total = 0 n = 1 while total < 20: total = total + n n = n + 1 print(n)8.The subtraction here takes the variable past the condition and keeps going. What does the program print?
n = 27 while n > 0: n = n - 4 print(n)
Answer key — Grade 9 Computer Science — Repeating while something is true
- 1. 1. Starts at 10 and has 9 added each time 2. Starts at 6 and has 15 added each time 3. Starts at 2 and is multiplied by 3 each time 4. Starts at 1 and is doubled each time
- 2. 32
- 3. Multiplied by 2 each time → 128; Multiplied by 3 each time → 243; Multiplied by 5 each time → 125; Multiplied by 10 each time → 100; Multiplied by 4 each time → 256
- 4. a) 5
- 5. 4
- 6. 4
- 7. 7
- 8. -1