Given two numbers, Swap those two numbers with temporary variable.
What You'll Learn:
\n
for newline in output// Initial state: a=2, b=36
long long a = 2, b = 36, temp;
// Step 1: Save 'a' to temporary variable
temp = a; // temp=2, a=2, b=36
// Step 2: Copy 'b' to 'a'
a = b; // temp=2, a=36, b=36
// Step 3: Copy temp to 'b'
b = temp; // temp=2, a=36, b=2
// Final state: a=36, b=2 ✓ Swapped!
a = b
first,
the original value of a
is overwritten and lost forever. The temp variable
acts like a safe storage to preserve the value during the swap.
// Think of it like swapping drinks between two cups:
// Cup A has Coffee ☕, Cup B has Tea 🍵
// You need an empty Cup (temp) to swap them!
temp = a; // Pour Coffee into empty cup
a = b; // Pour Tea into Cup A
b = temp; // Pour Coffee into Cup B
// Result: Cup A has Tea 🍵, Cup B has Coffee ☕
long long a = 2, b = 36;
a = b; // a=36, b=36 (original 'a' lost!)
b = a; // a=36, b=36 (both have same value!)
// ❌ Failed! Both variables now equal 36
While we use a temp variable here, there are other methods (for reference):
temp = a;
a = b;
b = temp;
a = a + b; // a=38, b=36
b = a - b; // a=38, b=2
a = a - b; // a=36, b=2
// Risk: Can overflow with large numbers!
a = a ^ b;
b = a ^ b;
a = a ^ b;
// Clever but less readable!
#include <algorithm>
swap(a, b); // Built-in function!
Swapping is fundamental in:
Mastering this simple pattern is essential - you'll use it countless times in your programming journey!
#include <iostream>
using namespace std;
int main() {
long long a, b, temp;
cin >> a >> b;
temp = a;
a = b;
b = temp;
cout << "num1=" << a << "\nnum2=" << b;
return 0;
}