While Loop CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumWrite a WHILE loop that asks the user for input until they type 'quit'.
Solution
- 1 Step 1: SET input = ''. WHILE input != 'quit': input = GET_INPUT('Enter command: '). PROCESS(input).
- 2 Step 2: The loop continues asking until the user types 'quit'.
- 3 Step 3: This is an input validation / sentinel value pattern โ 'quit' is the sentinel that stops the loop.
Answer
WHILE input != 'quit': input = GET_INPUT(). Uses a sentinel value to control the loop.
WHILE loops are ideal when we do not know in advance how many iterations are needed. The sentinel value pattern is commonly used for user input and data processing.
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 1 medium
Trace: SET n = 1. WHILE n < 100: n = n * 2. OUTPUT n. How many iterations?
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