Write void swapRef(int& a, int& b) so that it swaps the two variables it is given. main reads two numbers, swaps them with your function, and prints them.
What to build
A swap function that takes its arguments by reference.
Requirements
- Declare the parameters as
int&. - Use a third variable to swap them.
- Let
mainprint the swapped values.
Input
Two whole numbers on one line.
Output
The two numbers in swapped order, separated by a space.
Constraints
The numbers fit in an int.
Example
Input:
3 8
Output:
8 3
Why it works
Reference parameters are other names for the caller's variables, so swapping them swaps the originals.
Examples
Example 1 · Input
3 8
Expected output
8 3
Example 2 · Input
-1 1
Expected output
1 -1
Hints
Hint 1
The parameters are int& a and int& b: changing a changes the caller's variable.
Hint 2
Use a third variable: int t = a; a = b; b = t;
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
void swapRef(int& a, int& b) {
int t = a;
a = b;
b = t;
}
int main() {
int x, y;
cin >> x >> y;
swapRef(x, y);
cout << x << " " << y << endl;
return 0;
}