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
mediumSolution
- 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 Step 2: After reaching 128, the condition 128 < 100 is false, so the loop stops.
- 3 Step 3: The loop doubled n seven times, so the output is 128 after 7 iterations.
Answer
Example 2
mediumPractice Problems
Try these problems on your own first, then open the solution to compare your method.
Example 1
mediumExample 2
mediumBackground Knowledge
These ideas may be useful before you work through the harder examples.