What is printed by the print statements in the program assuming call by reference parameter passing?
Program P1()
{
x = 10;
y = 3;
func1(y,x,x);
print x;
print y;
}
func1(x,y,z)
{
y = y + 4;
z = x + y + z
}View worked solution
Answer: B
In call-by-reference parameter passing, the formal parameters of the called function become aliases (references) to the actual arguments passed from the calling function. Any modification to the formal parameters directly updates the actual arguments.
1. Mapping Parameters
In P1(), we have the variables:
x = 10y = 3
The function call is func1(y, x, x). In func1(x, y, z), the formal parameters map to the actual variables as follows:
- Formal parameter
xis a reference to actual variableyofP1. - Formal parameter
yis a reference to actual variablexofP1. - Formal parameter
zis also a reference to actual variablexofP1.
Thus, both y and z in func1 are aliases for the same variable x in P1.
2. Step-by-Step Execution of func1
-
Statement 1:
y = y + 4;Since formal
\nyrefers toP1.x:Now,
P1.xbecomes . Since formalzalso refers toP1.x, the value accessed viazis now also . -
Statement 2:
z = x + y + z;Substituting the references (formal
xrefers toP1.y, and formalsyandzrefer toP1.x):
3. Final Output
After returning to P1():
print x;outputs 31print y;outputs 3
Therefore, the printed values are 31, 3.
Free practice · Your answers on this page are not saved.
