Variable CS Thinking Example 2

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

Example 2

medium
Show how to swap the values of two variables a and b using a temporary variable. Trace with a = 5, b = 9.

Solution

  1. 1
    Step 1: SET temp = a. Now temp = 5, a = 5, b = 9.
  2. 2
    Step 2: SET a = b. Now temp = 5, a = 9, b = 9.
  3. 3
    Step 3: SET b = temp. Now temp = 5, a = 9, b = 5. Values swapped.

Answer

After swap: a = 9, b = 5. Use a temporary variable to avoid overwriting.
Swapping without a temporary variable would lose one value. The temp variable acts as a holding space โ€” a classic pattern in programming.

About Variable

A named container in a program that stores a value, which can be read, updated, or replaced. Variables have a name (identifier), a value (the data stored), and in many languages a type (what kind of data it holds).

Learn more about Variable โ†’

More Variable Examples