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 for each item in a collection.

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.

Worked Examples

Example 1

easy
Trace: FOR i = 0 TO 4: OUTPUT i * i.

Solution

  1. 1
    Step 1: i=0: output 0. i=1: output 1. i=2: output 4.
  2. 2
    Step 2: i=3: output 9. i=4: output 16.
  3. 3
    Step 3: Outputs: 0, 1, 4, 9, 16 (perfect squares).

Answer

0, 1, 4, 9, 16
FOR loops are used when the number of iterations is known in advance. The loop variable automatically increments each iteration.

Example 2

medium
Convert this FOR loop to a WHILE loop: FOR i = 1 TO 5: OUTPUT i.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
Write a FOR loop that calculates 5! = 5 \times 4 \times 3 \times 2 \times 1.

Example 2

medium
What does this code output? SET 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

Related Concepts

Background Knowledge

These ideas may be useful before you work through the harder examples.

iterationwhile loop