Consider the following program fragment, If the program is run, what would be th
ID: 3877444 • Letter: C
Question
Consider the following program fragment, If the program is run, what would be the output? Explain your answer. To get full marks, you need to show all working. [3 Points]
#include <iostream>
using namespace std;
//function prototype
void ParamTest(int, int&);
int main()
{
int p1 = 2;
int p2 = -5;
ParamTest(p1, p2);
cout << p1 << " " << p2 << endl;
return 0;
}
//function body
void ParamTest(int a, int &b)
{
b = b - a;
a = 2 * a + (b - 2);
}
Explanation / Answer
the output is 2 -7
====================
[2 is the value of p1 and -7 is the value of p2]
Explaination:
=============
Comments are given beside the code to better understand.
The code has a function called ParamTest() which takes 2 parameters. The 1st parameter is passed by value, so any changes to it is local to the function and will not be seen by the calling main() function. The 2nd parameter is passed by reference, so any changes to it is also seen in calling function main() after the ParamTest() function returns.
Initially main() passes p1 = 2 and p2 = -5 to ParamTest(). In ParamTest(), p2 gets modified to difference b = b- a = -5-2 = -7. The 1st parameter a of ParamTest = 2 * a + (b-2) = 2 * 2 + (-5-2) = 4 - 7 = -3. But changes to 1st parameter are local and lost when then function returns. So when the function reutrns, p1 = 2, p2 = -7. So the output is 2 -7
Commented code
==============
#include <iostream>
using namespace std;
//function prototype
void ParamTest(int, int&); //second parameter is passed by reference, any change to the 2nd parameter will be seen in calling function
int main()
{
int p1 = 2;
int p2 = -5;
//1st parameter = 2 and 2nd parameter = -5, function signature shows 2nd parameter is pass by reference
//so changes to 2nd parameter will be seen in main when the function returns
ParamTest(p1, p2);
cout << p1 << " " << p2 << endl;
return 0;
}
//function body
void ParamTest(int a, int &b)
{
b = b - a; //modify the 2nd parameter to difference of 2nd and 1st parameter, 2nd parameter is passed by ref, so changes will be preserved
a = 2 * a + (b - 2); //update 1st parameter, but its pass by value, so the changes are lost when function returns
}