retagged by
12,251 views
27 votes
27 votes

What is printed by the print statements in the 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
}
  1. $\text{10, 3}$
  2. $\text{31, 3}$
  3. $\text{27, 7}$
  4. None of the above
retagged by

4 Answers

Best answer
42 votes
42 votes
Answer is B.

Here, variable $x$ of func1 points to address of variable $y.$

and variables $y$ and $z$ of func1 points to address of variable $x.$

Therefore, $y=y+4 \implies y=10+4 = 14$

and $z=x+y+z \implies z=14+14+3=31$

$z$ will be stored back in $x.$  Hence, $x=31$ and $y$ will remain as it is. $(y=3)$

Answer is $31, 3$
selected by
11 votes
11 votes
Program P1()
{
    x = 10;
    y = 3;
    func1(y,x,x);
    print x;
    print y;
}

/* It's the call by reference. */

/* So func1(x,y,z)'s parameters x, y, z will respectively contain */
/* the address of the original parameters */

/* It means calling func1(y,x,x), */
/* the parameter x contains y, y contains x and z contains x. */



func1(x,y,z) /*  (y,x,x) = (10,3,3)  */
{
    y = y + 4;   /* x = x + 4  */ 
                 /*   = 10 + 4 */
                 /*   = 14     */
    
    z = x + y + z   /* x = y + x + x   */
                    /*   = 3 + 14 + 14 */
                    /*   = 31          */
}

/* Here the value of y is unaffected. */
/* Just the value of x is changed. */

 

$\therefore$ It's $x=31, y = 3$ as the final output.

So the correct answer is B.
 

edited by
2 votes
2 votes

Call by reference : Whenever Calling a Function , rather than passing the variables value we pass it’s address instead to the function. 

Also we know that to store an address , a pointer is required . So the function parameters must have pointers .  

The same program can be rewritten as :

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
}

 

1 votes
1 votes
z=x+y+z;  here z=3+14+14; is the right order so z=31 since func1(y,x,x) is the function call and both y and z in function definition func1(x,y,z) , point to x and x

And x point to y and in this function definition there is no change in x value means in value of y because here x point to y and there ,in function definition func1(x,y,z), is no equation for change in x, it is only contain y and z change.

i.e. func1(x,y,z)

{ y=y+4; so y=10+4;

z=x+y+z; so z=3+14+14;

}

So finally in Program P1()

print x; 31

print y; 3
Answer:

Related questions