What is printed by the print statements in program P1, assuming…

2001

What is printed by the print statements in program P1, 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;
}

Answer: B. 31, 3Call-by-reference rule: each formal parameter becomes an alias for the actual argument passed to it. For the call func1(y, x, x): formal x aliases P1.y (value…

  1. A.

    10, 3

  2. B.

    31, 3

  3. C.

    27, 7

  4. D.

    None of the above

Attempted by 10 students.

Show answer & explanation

Correct answer: B

Call-by-reference rule: each formal parameter becomes an alias for the actual argument passed to it.

For the call func1(y, x, x):

  • formal x aliases P1.y (value 3).

  • formal y aliases P1.x (value 10).

  • formal z also aliases P1.x because the third actual argument is again x.

Step 1: y = y + 4. Here formal y is an alias for P1.x, so P1.x becomes 10 + 4 = 14.

Step 2: z = x + y + z. Now formal x is P1.y = 3, while formal y and z both refer to P1.x = 14. So the value assigned to z is 3 + 14 + 14 = 31. Since z aliases P1.x, P1.x becomes 31.

P1.y was never assigned a new value, so it remains 3.

Output: 31, 3

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…