In: Computer Science
I ALREADY HAVE THE CORRECT ANSWERS. CAN YOU EXPLAIN TO ME HOW AND/OR WHY THESE ARE THE ANSWERS? THANK YOU :)
int a(int &x, int y) { x = y; y = x + 1; return y;
}
int b(int &x, int y) { y = x + 1; x = y; return y;
}
void c(int x, int y) { if (x > 2) return; cout << y; c(x + 1, y - 1);
}
int main() {
int x[2][3] = {{1, 2, 3}, {4, 5, 6}};
int y[3] = {7, 8, 9};
cout << x[1][1] << endl; // line (a)
y[0] = a(y[0], y[1]);
cout << y[0] << y[1] << endl; // line (b)
cout << b(x[0][2], x[1][2]) << endl; // line (c)
cout << x[0][2] << x[1][2] << endl; // line (d)
c(0, 4); cout << endl; // line (e)
}
(a) What is the output from the instruction beginning on line (a)?
Answer: 5
(b) What is the output from the instruction beginning on line (b)?
Answer: 98
(c) What is the output from the instruction beginning on line (c)?
Answer: 4
(d) What is the output from the instruction beginning on line (d)?
Answer: 46
(e) What is the output from the instruction beginning on line (e)?
Answer: 432
a) x[1][1] refers to element present in 2nd row and 2nd column i.e. 5.
b) when we use call by reference, changes in function parameter are reflected on actual parameters(outside function) i.e. if we send some variable by call by reference to function and we made some changes to that variable inside function , then that changes will get reflected on actual variable which means value of actual variable will get over written by new value.
here y[0]=7 and y[1]=8 sent to function a;
In function
&x=y[0]=7 (call by reference)
y=y[1]=8
x=y(means value of y(i.e 8) will be copied to x(here value of x changed from 7 to 8 as well as value of y[0] is also changed to 8)
y=x+1(y=8+1 i.e y=9)
return y(here y will be returned to main function and value present in y will be stored in y[0])
therefore output of line b
cout << y[0] << y[1] << endl;
output
98
c)Same happen in this part also
x[0][2]=3
x[1][2]=6
in function b
&x=x[0][2]=3
y=x[1][2]=6
y=x+1(y=3+1 i.e y=4)
x=y(x=4 as well as x[0][2]=4)
return y(value of y(i.e. 4 ) will be returned to main function)
therefore output will be 4
d.) Now according to new x ,
x[0][2]=4
x[1][2]=6
therefore output of line d is 46