🚀
ArkyEdu GLOSAR TIC
RO Practice Lab
Algorithms, C++ & Scratch Grades 5–7 RO Term: Regula celor 3 Pahare (Interschimbarea Valorilor în C++)

Swap Algorithm (Temporary Variable / 3-Cups Rule)

💬 Share on WhatsApp
📌 Quick Definition (Answer-First)

Swapping the values of two variables a and b without overwriting data requires a third temporary variable (temp): temp = a; a = b; b = temp;.

How It Works & Why It Matters

Imagine swapping juice in cup A and water in cup B—you need an empty third cup (temp) first so neither liquid spills or mixes.

This 3-line pattern is the building block of all sorting algorithms.

💻 Standard 3-Line Swap in C++
int a = 5, b = 9, temp;
temp = a; // Save 5
a = b;    // a becomes 9
b = temp; // b becomes 5

🏫 Classroom Example

To ensure a <= b before a loop: if (a > b) { int temp = a; a = b; b = temp; }

⚖️ Direct Copy vs. Swap

a = b overwrites a permanently; using temp preserves both values across the exchange.

⚠️ Common Mistake in Exams & Homework

Writing a = b; b = a; directly—both variables end up holding b’s original value.

❓ Quick Questions & Answers

Why do you need a temporary variable to swap values?
Because assigning a = b destroys a’s old value unless it was backed up in temp beforehand.

Related Glossary Terms

← Back to Full Glossary (A–Z)