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
easySolution
- 1 Step 1: i=0: output 0. i=1: output 1. i=2: output 4.
- 2 Step 2: i=3: output 9. i=4: output 16.
- 3 Step 3: Outputs: 0, 1, 4, 9, 16 (perfect squares).
Answer
Example 2
mediumPractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
mediumRelated Concepts
Background Knowledge
These ideas may be useful before you work through the harder examples.