While Loop Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of While 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 as long as a specified condition remains true.

A while loop is like 'keep going until...' โ€” keep stirring the soup WHILE it's not boiling. Keep asking for a password WHILE the password is wrong.

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: While loops check the condition before each iteration. If the condition is false from the start, the body never executes.

Common stuck point: Forgetting to update the loop variable creates an infinite loop. Always make sure the condition will eventually become false.

Worked Examples

Example 1

medium
Trace: SET n = 1. WHILE n < 100: n = n * 2. OUTPUT n. How many iterations?

Solution

  1. 1
    Step 1: Start at n = 1 and double each time: 1 \to 2 \to 4 \to 8 \to 16 \to 32 \to 64 \to 128.
  2. 2
    Step 2: After reaching 128, the condition 128 < 100 is false, so the loop stops.
  3. 3
    Step 3: The loop doubled n seven times, so the output is 128 after 7 iterations.

Answer

Output: 128. 7 iterations.
A WHILE loop repeats as long as its condition is true. The condition is checked before each iteration, so the loop may execute zero or more times.

Example 2

medium
Write a WHILE loop that asks the user for input until they type 'quit'.

Practice Problems

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

Example 1

medium
Trace: SET total = 0. SET i = 1. WHILE i <= 4: total = total + i. i = i + 1. OUTPUT total.

Example 2

medium
Trace this code and state the final output: SET n = 1 SET result = 1 WHILE n < 5 SET n = n + 1 SET result = result * n END WHILE OUTPUT result

Related Concepts

Background Knowledge

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

iteration