retagged by
2,057 views
4 votes
4 votes

Consider the following program in Pseudo-Pascal syntax.

program what:
    var z: integer
    procedure recur(x):
    begin if x <= 40 then
        begin x:x+z
            recur(x);
            z:=x+10
        end
    end(*recur*)
begin(*what*)
    z=10;
    recur(z);
    writeln(z)
end
  1. Suppose the parameter to the procedure ‘recur’ is passed by value.

    1. What value is printed by program?

    2. How many times is ‘recur’ called?

  2. What value is printed by the program if the parameter is passed by reference?

retagged by

1 Answer

Best answer
5 votes
5 votes
a.

rec 1: x = 10, z = 10, x = x + z = 20
rec 2: x = 20, z = 10, x = x + z = 30
rec 3: x = 30, z = 10, x = x + z = 40
rec 4: x = 40, z = 10, x = x + z = 50
rec 5: x = 50, if fails rec ends
rec 4: z = x + 10 = 60
rec 3: z = x + 10 = 50
rec 2: z = x + 10 = 40
rec 1: z = x + 10 = 30

So,

(i) 30 is printed
(ii) recur is called 5 times.

b.  

Pass by reference means x and z have the same memory and hence share the value at any point.

rec 1: x = 10, z = 10, x = x + z = 20
rec 2: x = 20, z = 20, x = x + z = 40
rec 3: x = 40, z = 40, x = x + z = 80
rec 4: x = 80, if fails rec ends
rec 3: z = x + 10 = 90
rec 2: z = x + 10 = 90 + 10 = 100
rec 1: z = x + 10 = 100 + 10 = 110

So, 110 is printed.
selected by

Related questions

13 votes
13 votes
2 answers
3
Kathleen asked Sep 15, 2014
8,177 views
The results returned by function under value-result and reference parameter passing conventionsDo not differDiffer in the presence of loopsDiffer in all casesMay differ i...