For Loop Examples in CS Thinking
Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of For Loop.
This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.
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.
A for loop is like 'do this for each...' β for each student in the class, print their name. For each number from 1 to 10, add it to the total.
Read the full concept explanation βHow to Use These Examples
- Read the first worked example with the solution open so the structure is clear.
- Try the practice problems before revealing each solution.
- Use the related concepts and background knowledge badges if you feel stuck.
What 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.
Sense of Study hint: When using a for loop, first identify what you are iterating overβa range of numbers or a collection of items. The loop variable is automatically assigned each value in turn. Remember that range(n) produces 0 to n-1 (not 1 to n), and check your loop bounds carefully.
Worked Examples
Example 1
easyAnswer
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 these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
mediumExample 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
challengeRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.