GATE / CS ARCHIVE

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

Count value-parameter procedure calls

Programming in C · Functions & Parameter Passing · Full GATE CSE 1997 paper

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

Functions & Parameter Passing

Question 10(a)(ii), 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, how many times is recur called, including the call from the main program?
Question 10(a)(ii), 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, how many times is recur called, including the call from the main program?
Question 10(a)(ii), 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, how many times is recur called, including the call from the main program?
Tap to enlarge
Answer & solution

Answer: 5 total calls, of which 4 are recursive calls. (no official key was published)

Step through it (13 steps)

At every recursive descent, the global z is still 10, since z is assigned only after recur(x) returns. Each active call therefore adds 10 to its own copy of x and invokes the next call. The entry arguments are

Main → recur(10) → recur(20) → recur(30) → recur(40) → recur(50).

The first four entries satisfy x≤40 and execute the recursive-call statement. The last entry, with x=50, fails the test and returns without another call. It is nevertheless an invocation and must be included when counting how many times recur is called. Thus there are five calls in total, four of them made recursively by the procedure itself.

A count of four confuses the number of executed recursive-call statements, or the number of nonbase activations, with the total requested calls. A count based on doubling x would instead be using reference semantics, in which x aliases z; that is not this subpart. The literal ≤ is also essential: a call with argument 40 recurses once more. Original10(a)(ii) is a separate normalized leaf, but neither source prints its own mark allocation, so its marks remain null.

Original paper, page 7