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.
A loop is like running laps with a coach holding a clipboard. Before each lap the coach checks the rule, say 'fewer than 4 laps done?', and you run again only if the answer is yes. Each lap adds a tick to the clipboard. Forget the tick and the coach will keep you running forever.
Showing a random 20 of 50 problems.
Example 1
hard
A while loop with condition i<10 but i 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= '' ; for c in 'abc': s=s+c. Final s?
Example 7
hard
Trace: list = [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=1; repeat 4 times: t=a+b; a=b; b=t. Final b?
Example 10
easy
Trace: s=0; for i in 1,2,3: s=s+i. Final s?
Example 11
easy
Trace: FOR i = 1 TO 4: OUTPUT i * 2.Trace: FOR i = 1 TO 4: OUTPUT i * 2
Example 12
challenge
Trace: n=27; count = 0; while n>1: if n even: n=n//2; else: n=3⋅n+1; count += 1. What is count when the loop ends? (Collatz)
Example 13
medium
Trace: s=0; for i in range(1, 11): s=s+i. Final s?
Example 14
easy
Trace: s=0; for i in 1,2,3,4: s=s+i. Final s?
Example 15
easy
How many times does 'for i in range(6)' run the body?
Example 16
medium
Trace: s=0; for i in 1..10: if imod2==1: s=s+i. Final s?
Example 17
easy
Trace: p=1; for i in 1,2,3: p=p∗2. Final p?
Example 18
challenge
A list [1,2,3,4]; a loop removes every element while iterating index 0..len. Why does this skip elements?
Example 19
medium
Trace: s=0; for i in range(4): s=s+i (range(4) is 0,1,2,3). Final s?
Example 20
medium
A loop sums even numbers in [1,2,3,4,5,6]. Trace and give the total.