Question
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 ________.
Official answer and solution
- Official answer
- 3
- From
- Official GATE 2016 answer key
Solution
Trace the recursive execution of the function to see that it computes the maximum difference between any two adjacent elements.
The recursive function is defined as:
int f(int *p, int n) {
if (n <= 1) return 0;
else return max(f(p+1, n-1), p[0] - p[1]);
}
Unrolling the recursion for an array of size :
It computes the maximum adjacent difference across the array, bounded below by 0.
Given array of size 5:
- :
- :
- :
- :
Evaluate the maximum:
Therefore, the value printed by the program is 3.
3
Confusing adjacent difference with absolute difference or with maximum element in the array.
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2016 Computer Science and Information Technology (CS) Session 2
- Question
- 47 of 65, printed as CS Q.37
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.