While Loop CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

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

Solution

  1. 1
    Step 1: SET input = ''. WHILE input != 'quit': input = GET_INPUT('Enter command: '). PROCESS(input).
  2. 2
    Step 2: The loop continues asking until the user types 'quit'.
  3. 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