Programming Languages: Sample Final Exam

Many thanks to Paul Bethe, who found a number of errors in my first set of solutions.

Problem 1

Consider the following pseudo-code in an imperative language:
int x = 1, n = 10;

function f () {
   int x = 3;
    
   function g (int c,d) {
      c = c-1;
      print(c,d,x,n);
    } /* end of g */

/* body of f */
    g(x,x);
} /* end of f */

function h () {
   int n = 2;

  f();
} /* end of h */

main()  { h(); }

Problem 2

A two-dimensional array may be implemented as a "true" two-dimensional array or as an array of pointers to one-dimensional arrays. Suppose that For each of the two implementations, explain what steps are involved at run-time in computing the address of the expression A[I,J]. (Ignore bounds checking).
Answer: For a true multi-dimensional array, the address of A[I,J]is at 1000+((I*100)+J)*50. For a ragged array, the address of A[I,J] is at (dereference(1000+I)) + J*50.

Problem 3

Problem 4

Consider the following Ada code framework. There is one client and ten servers. The client computes a series of ten questions and asks one question to each server. The server first returns a quick answer (perhaps just an acknowledgement) and then thinks at greater length and returns a more thoughtful answer.

type query = ... end;
type answer = ... end;

task type server is
   entry request(q: in query; a: out answer);
   entry returnAnswer(a: out answer);
end

task body server is
qy : query;
an: answer;
begin accept request(q: in query, a: out answer) do
          qy = q;
          an := quickAnswer(q);
        end request
        an := thoughtfulAnswer();
        accept returnAnswer(out an: answer)
          end returnAnswer;
      end loop;
end server;

procedure client is
s: array (1 .. 10) of server;
m : message;
a : answer;
begin for i in 1 .. 10 loop
         m := computeMessage(i);
         s[i].request(m,a);
       end loop
      for i in 1 .. 10 loop
         s[i].returnAnswer(a);
         incorporateAnswer(a);
      end loop
end client;
Assume that the functions "quickAnswer", "thoughtfulAnswer", "computeMessage", and "returnAnswer" are defined elsewhere.

For each of the following pairs of activity P,Q state whether P must occur before Q, Q must occur before P, or P and Q can proceed in parallel:

Problem 5

If an object has been allocated on the heap but is no longer accessible then its space should be reclaimed as free space on the heap.

Problem 6:

In Java the type "int" and the type "Integer" are quite different.

Problem 7:

Consider the following fragment of Ada code:
type Distance is new Float;
subtype Small is Float range 0.0 .. 1.0; -- erroneously written as
                                         -- 0.0 to 1.0 in original handout.

procedure P is

F: Float;
D,E : Distance;
S : Small;
J: Integer;

begin for I in 1 .. 10 loop
         J := I * 12;
         D := D * I;
         F := 0.5 * I;
         S := F;
         E := S;
       end loop;    
end P;