Variable CS Thinking Example 4

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

Example 4

medium
Trace this swap algorithm: SET A = 3. SET B = 8. SET temp = A. SET A = B. SET B = temp. What are A and B at the end, and why is temp needed?

Solution

  1. 1
    Step 1: temp stores the original value of A, so temp = 3. Then A is replaced with B, so A = 8.
  2. 2
    Step 2: Finally B is set to temp, so B = 3. The temporary variable is needed so the original value of A is not lost during the swap.

Answer

A = 8 and B = 3. The variable temp temporarily stores A so the values can be swapped safely.
Variables hold values that can be updated during a program. Temporary variables are often used when data must be preserved while other assignments happen.

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