retagged by
22,329 views
68 68 votes

Consider the following program:

int f (int * p, int n) 
{ 
    if (n <= 1) return 0; 
    else return max (f (p+1, n-1), p[0] - p[1]); 
}
 int main () 
{
    int a[] = {3, 5, 2, 6, 4}; 
    printf(" %d", f(a, 5)); 
}

Note: $\max (x, y)$ returns the maximum of $x$ and $y$.

The value printed by this program is ________.

10 Answers

Best answer
92 92 votes

$f(a,5)$

  • $p$ , $n=5.$ $\begin{array}{|l|l|l|l|l|} \hline 3 & 5 & 2 &  6 &   4 \\\hline \end{array}$
    $\max(f(p+1,5-1),3-5) = \max(f(p+1,4),-2)$
  • $p$ , $n=4. \begin{array}{|l|l|l|l|} \hline 5 & 2 &  6 &   4 \\\hline \end{array}$
    $\max(\max(f(p+1,4-1),5-2),-2)=\max(\max(f(p+1,3),3),-2)$
  • $p$ , $n=3. \begin{array}{|l|l|l|} \hline 2 &  6 &   4 \\\hline \end{array}$
    $\max(\max(\max(f(p+1,3-1),2-6),3),-2) =\max(\max(\max(f(p+1,2),-4),3),-2)$
  • $p$ , $n=2.\begin{array}{|l|l|} \hline 6 &   4 \\\hline \end{array}$
    $\max(\max(\max(\max(f(p+1),1),2),-4),3),-2)$
  • $n=1$, return $0$

$\max(\max(\max(\max(0,2),-4),3),-2)$

$=\max(\max(\max(2,-4),3),-2)$

$=\max(\max(2,3),-2)$

$=\max(3,-2)$

$=3$

edited by
45 45 votes

Ans is 3

3 3 votes
It can easily be solved by observing the code.

Here in the code they are trying to figure out max(array[i]-array[i-1])

so answer will be max(a[0]-a[1],a[1]-a[2],a[2]-a[3],a[3]-a[4])

                          = max(3-5,5-2,2-6,6-4)

                         = max(-2,3,-4,2)

                         = 3
Answer:
Position:
Show:

Related questions

45 45 votes
8 answers 8 answers
14.2k
14.2k views
Akash Kanase asked Feb 12, 2016
14,192 views
The value printed by the following program is _______.void f (int * p, int m) { m = m + 5; *p = *p + m; return; } void main () { int i=5, j=10; f (&i, j); p...
141 141 votes
15 answers 15 answers
39.4k
39.4k views
Akash Kanase asked Feb 12, 2016
39,427 views
Suppose the functions $F$ and $G$ can be computed in $5$ and $3$ nanoseconds by functional units $U_{F}$ and $U_{G}$, respectively. Given two instances of $U_{F}$ and two...
35 35 votes
2 answers 2 answers
14.3k
14.3k views
Akash Kanase asked Feb 12, 2016
14,252 views
Consider the following processes, with the arrival time and the length of the CPU burst given in milliseconds. The scheduling algorithm used is preemptive shortest remain...
73 73 votes
8 answers 8 answers
27.3k
27.3k views
Akash Kanase asked Feb 12, 2016
27,323 views
The width of the physical address on a machine is $40$ bits. The width of the tag field in a $512$ KB $8$-way set associative cache is ________ bits.