While Loop CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
mediumTrace: SET n = 1. WHILE n < 100: n = n * 2. OUTPUT n. How many iterations?
Solution
- 1 Step 1: Start at and double each time: .
- 2 Step 2: After reaching , the condition is false, so the loop stops.
- 3 Step 3: The loop doubled seven times, so the output is after 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.
About While Loop
A control structure that repeats a block of code as long as a specified condition remains true. The condition is checked before each iteration, and if it is false from the start, the loop body never executes at all.
Learn more about While Loop โMore While Loop Examples
Example 2 medium
Write a WHILE loop that asks the user for input until they type 'quit'.
Example 3 mediumTrace: SET total = 0. SET i = 1. WHILE i <= 4: total = total + i. i = i + 1. OUTPUT total.
Example 4 mediumTrace this code and state the final output: SET n = 1 SET result = 1 WHILE n < 5 SET n = n + 1