For Loop Examples: 48 Problems with Answers
Worked examples of For Loop to try before you open each solution, then practice problems with answers.
Worked Examples
Example 1
easyShow solution
Answer
First step
Full solution
- 2. Step 2: i=3: output 9. i=4: output 16.
- 3. Step 3: Outputs: 0, 1, 4, 9, 16 (perfect squares).
Example 2
mediumExample 3
mediumExample 4
mediumExample 5
mediumExample 6
mediumExample 7
mediumExample 8
mediumExample 9
mediumExample 10
hardExample 11
hardExample 12
hardExample 13
challengePractice Problems
Try each one, then open the solution to compare your method.
Example 1
mediumExample 2
mediumSET scores = [85, 92, 78, 95, 88]
SET highest = scores[0]
FOR i = 1 TO LENGTH(scores) - 1
IF scores[i] > highest THEN
SET highest = scores[i]
END IF
END FOR
OUTPUT highest
Example 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
easyExample 10
easyExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
mediumExample 19
mediumExample 20
challengeExample 21
challengeExample 22
challengeExample 23
easyExample 24
easyExample 25
easyExample 26
easyExample 27
easyExample 28
easyExample 29
mediumExample 30
mediumExample 31
mediumExample 32
mediumExample 33
hardExample 34
hardExample 35
challengeWhat to focus on
Core idea: For loops are best when you know how many times to repeat or when iterating over a collection. The loop variable takes each value automatically.
Common stuck point: range(5) gives 0 to 4, not 1 to 5. Off-by-one errors are the most common for-loop bug.
Ask yourself: Do you know before the loop starts exactly what it goes through: a fixed count, or every item of a list or string?
Concept recap
A control structure that repeats a block of code a specific number of times or once for each item in a collection. The loop variable is automatically set to each successive value in the range or collection, eliminating the need to manually update it.
Dealing cards around a table is a for loop: one card to each player, and the round ends when every player has one, with nobody counting aloud. The players are the collection and dealing a card is the body. The picture also predicts the classic bug: if a player leaves mid-round, as when you remove items while looping, someone gets skipped.
Read the full lesson on For LoopRelated concepts
Background knowledge
These ideas may be useful before you work through the harder examples.