GATE / CS ARCHIVE

GATE CSE 1997 / QUESTION 10(a)(i)

Trace value-parameter recursion

Programming in C · Recursion · Full GATE CSE 1997 paper

GATE 1997, Q10(a)(i) Descriptive
Report issue

Recursion

Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Question 10(a)(i), GATE 1997: Consider this pseudo-Pascal program, where z is global:
program what;
var z:integer;
procedure recur(x);
begin
  if x<=40 then begin
    x:=x+z;
    recur(x);
    z:=x+10
  end
end;
begin
  z:=10;
  recur(z);
  writeln(z)
end.
If x is passed by value, what is printed?
Tap to enlarge
Answer & solution

Answer: 30. (no official key was published)

Step through it (13 steps)

Pass by value gives every call its own local x, but all calls still share the same global z. It is important not to copy z into each activation or to overwrite a caller's x with its child's final x.

On descent, no assignment z:=x+10 has executed yet: it comes after the recursive call. Therefore z stays 10 while the successive calls enter with x=10,20,30,40,50. The calls entering with 10,20,30,40 first update their local x to 20,30,40,50 respectively. The final call enters with x=50; because 50≤40 is false, it immediately returns.

Now unwind the suspended calls:
Entered x=40, saved updated x=50: assign z=60.
Entered x=30, saved updated x=40: assign z=50.
Entered x=20, saved updated x=30: assign z=40.
Entered x=10, saved updated x=20: assign z=30.

The outer call is last to write the shared global, so writeln(z) prints 30. The temporary value 60 produced by the deepest active body is not the final answer. Also, x=40 does execute its body, because both visual sources show ≤40 rather than <40. The individual marks for this nested leaf are not printed; they are left unknown rather than assigning an invented share of the original group's marks.

Original paper, page 7