Swap Two Numbers Using Reference
C++
Medium
5 views
Problem Description
Swap two variables using pass by reference.
Real Life: Like exchanging positions of two objects.
Step-by-Step Logic:
1. Use & in parameter to pass by reference
2. Changes in function affect original variables
3. Use temporary variable to swap
4. No return needed - original values changed
Official Solution
void swapNumbers(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void function_q9_pass_by_reference() {
int x = 10, y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swapNumbers(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!