Skip to content

Swap Three Numbers

Learning Objectives

  • Perform 3-variable cyclic swaps accurately.
  • Avoid assignment-overwrite mistakes.
  • Trace value movement step by step.

Concept Explanation

For three values A, B, C, swapping is usually done as rotation:

  • Clockwise: A->B, B->C, C->A
  • Anti-clockwise: A->C, C->B, B->A

Clockwise Algorithm

  1. temp = A
  2. A = C
  3. C = B
  4. B = temp

Example

Initial: A=1, B=2, C=3
Clockwise result: A=3, B=1, C=2

Common Mistakes

  • No temp variable, causing data loss.
  • Defining rotation goal incorrectly.
  • Forgetting to print both before/after values.

Practice Tasks

  1. Implement clockwise rotation.
  2. Implement anti-clockwise rotation.
  3. Extend to rotate 4 values.

Summary

Define target mapping first, then write assignments.