Swap Algorithm (Temporary Variable / 3-Cups Rule)
📌 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.
🚀 Practice in ArkyEdu Labs & Related Guides
🎮 Launch Interactive Lab →
Structura Liniară, Fluxul I/O (cin/cout) & Algoritmul celor 3 Pahare
📖 Full Lesson & Curriculum →
Clasa a VII-a · Structura Liniară & I/O C++
🏫 Grade 5 Hub →
All modules & guides for this grade
🏫 Grade 7 Hub →
All modules & guides for this grade
🏫 Grade 8 Hub →
All modules & guides for this grade
📚 Top 10 C++ Errors Fixed →
Troubleshoot the 10 most common C++ mistakes in Grades 7–8 (Code::Blocks): = vs ==, stray semicolons after if/while, infinite loops, 5/2 integer division, and n = 0.
❓ 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)Variable & C++ Data Types (int, double, char, bool) →
A variable is a named container in RAM that holds a value which can change while a program runs. In C++, every variable must be declared with a specific data type before use.
Algorithm & Core Algorithm Properties →
An algorithm is a finite, unambiguous, step-by-step set of instructions that transforms input data into the desired output within a finite number of steps.
Array (1D Vector) in C++ →
A 1D array is an indexed collection of elements sharing the same data type stored contiguously in memory under a single name. In C++, native array indices start at 0.
Modulo (%) & Integer Division (/) in C++ →
When both operands are integers in C++, / computes the integer quotient (discarding decimals), while modulo % returns the remainder. Together with base 10 (% 10 and / 10), they power digit-extraction and divisibility algorithms.