Practice Iteration in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick Recap

Repeating a block of instructions multiple times until a stopping condition is satisfied. Iteration is one of the three fundamental control structures (along with sequence and selection) and is implemented through while loops, for loops, and other looping constructs.

Do this again and again until some condition is met, then move on to the next step.

Showing a random 20 of 50 problems.

Example 1

hard
A while loop with condition i<10i < 10 but ii never changes inside. What problem and what fix?

Example 2

medium
What is the difference between break and continue?

Example 3

easy
Write pseudocode using a loop to output the numbers 5, 10, 15, 20, 25.

Example 4

medium
How many times does 'for i in range(2, 10, 2)' run? (start 2, stop 10, step 2)

Example 5

medium
Trace: SET count = 0. SET n = 1. WHILE n <= 10: IF n MOD 2 == 0 THEN count = count + 1. n = n + 1. OUTPUT count.

Example 6

hard
Trace string concatenation: s=s = '' ; for cc in 'abc': s=s+cs = s + c. Final ss?

Example 7

hard
Trace: list = [4,2,7,1,8][4, 2, 7, 1, 8]. Compute average via iteration: sum then divide by count.

Example 8

easy
Fill in: A loop that runs a fixed known number of times is typically a ___ loop.

Example 9

challenge
Trace: a=0,b=1a=0,b=1; repeat 4 times: t=a+bt=a+b; a=ba=b; b=tb=t. Final bb?

Example 10

easy
Trace: s=0s=0; for ii in 1,2,31,2,3: s=s+is=s+i. Final ss?

Example 11

easy
Trace: FOR i = 1 TO 4: OUTPUT i * 2.

Example 12

challenge
Trace: n=27n = 27; count = 0; while n>1n > 1: if nn even: n=n//2n = n // 2; else: n=3โ‹…n+1n = 3 \cdot n + 1; count += 1. What is count when the loop ends? (Collatz)

Example 13

medium
Trace: s=0s = 0; for ii in range(1, 11): s=s+is = s + i. Final ss?

Example 14

easy
Trace: s=0s=0; for ii in 1,2,3,41,2,3,4: s=s+is = s + i. Final ss?

Example 15

easy
How many times does 'for i in range(6)' run the body?

Example 16

medium
Trace: s=0s = 0; for ii in 1..10: if iโ€Šmodโ€Š2==1i \bmod 2 == 1: s=s+is = s + i. Final ss?

Example 17

easy
Trace: p=1p=1; for ii in 1,2,31,2,3: p=pโˆ—2p = p * 2. Final pp?

Example 18

challenge
A list [1,2,3,4][1,2,3,4]; a loop removes every element while iterating index 0..len. Why does this skip elements?

Example 19

medium
Trace: s=0s=0; for ii in range(4): s=s+is = s + i (range(4) is 0,1,2,3). Final ss?

Example 20

medium
A loop sums even numbers in [1,2,3,4,5,6][1,2,3,4,5,6]. Trace and give the total.