Q16.Marks: +2.0UGC NET Paper 2: Computer Sc 23rd August 2024 Shift 1
#include < iostream.h >
using namespace std;
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 5, b = 10;
swap(a, b);
swap(a, b);
cout << a << " " << b;
return 0;
}
What will be the output of above code?
1.5, 10✓ Correct
2.10, 5
3.5, 5
4.10, 10
Solution
Correct answer is 5, 10
Concept:
Pass by Reference:
In C++, when we pass variables by reference to a function, any modifications made to the parameters affect the original variables. This is useful for functions like swap, where we need to exchange the values of two variables.
Explanation:
Let's analyze the provided code step by step:
#include <iostream.h>
using namespace std;
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 5, b = 10;
swap(a, b); // First swap: a becomes 10, b becomes 5
swap(a, b); // Second swap: a becomes 5, b becomes 10
cout << a << " " << b; // Output the values of a and b
return 0;
}
Breakdown of the code:
1. Initially, `a` is 5 and `b` is 10.
2. The first `swap(a, b)` is called:
`x` becomes 10 (value of `b`)
`y` becomes 5 (value of `a`)
After the first swap, `a` becomes 10 and `b` becomes 5.
3. The second `swap(a, b)` is called:
`x` now is 10 (the new value of `a`)
`y` now is 5 (the new value of `b`)
After the second swap, `a` becomes 5 and `b` becomes 10 again.
4. Finally, the output will be:
`cout << a << " " << b;` outputs 5 10.
Therefore, the output of the program will be: 1) 5, 10.