edited by
10,305 views
23 votes
23 votes

Consider these two functions and two statements S1 and S2 about them. 

int work1(int *a, int i, int j)
{
    int x = a[i+2];
    a[j] = x+1;
    return a[i+2] - 3;
}
int work2(int *a, int i, int j)
{
    int t1 = i+2;
    int t2 = a[t1];
    a[j] = t2+1;
    return t2 - 3;
}

S1: The transformation form work1 to work2 is valid, i.e., for any program state and input arguments, work2 will compute the same output and have the same effect on program state as work1 

S2: All the transformations applied to work1 to get work2 will always improve the performance (i.e reduce CPU time) of work2 compared to work1

  1. S1 is false and S2 is false
  2. S1 is false and S2 is true
  3. S1 is true and S2 is false
  4. S1 is true and S2 is true
edited by

3 Answers

Best answer
26 votes
26 votes

Consider an array a = 1 2 3 4 5 and condition i + 2 =j. Lets take i =0 and j =2 for this example.

Work 1, 

x = a[0+2] = 3

a[2] = 3 + 1 = 4;  which means a = 1 2 4 4 5

return a[0+2] - 3 = 4 -3 = 1

Work 2

t1 = 0 + 2 = 2

t2 = a[2] = 3

a[2] = 3 + 1 = 4, which means a = 1 2 4 4 5 again

return t2 - 3 = 3 -3 =0

Hence S1 is false when i + 2 =j. S2 will also be false, since we cant explicitly say the performance of work2 will always be better than work1.

Hence answer is A

selected by
9 votes
9 votes
answer - A

when j == i+2 programs will return different results
–1 votes
–1 votes
Ans- C

Only an extra variable t1 has been added in work 2 instead of directly computing the subscript as in work 1.The output will be same. S1 is true.

The addition of variables t1 and t2 will not improve the performance in anyway. i.e S2 is false.

Corrcet me I'm wrong
Answer:

Related questions

33 votes
33 votes
4 answers
4