Event Handler CS Thinking Example 2

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

Example 2

medium
Write pseudocode for a simple calculator with buttons for digits 0-9 and an '=' button. How would you use event handlers to build this?

Solution

  1. 1
    Step 1: SET display = ''. FOR each digit button (0-9): WHEN digitButton.clicked: display = display + digitButton.value.
  2. 2
    Step 2: WHEN equalsButton.clicked: result = EVALUATE(display). display = STRING(result).
  3. 3
    Step 3: Each button has its own event handler. The digit handlers append to the display string; the equals handler evaluates the expression. Multiple handlers work together to create the full calculator behaviour.

Answer

Each button has an event handler: digit buttons append their value to the display, equals button evaluates the expression.
Breaking interactive applications into event handlers is a form of decomposition. Each handler is simple, but together they create complex behaviour.

About Event Handler

A function that is automatically called when a specific event occurs, such as a button click, key press, or timer tick. The handler is registered (attached) to an event source once, and then the system invokes it every time that event fires.

Learn more about Event Handler โ†’

More Event Handler Examples