GATE | GATE CS 2010 | Question 35
#include<stdio.h> int f(int *a, int n) { if(n <= 0) return 0; else if(*a % 2 == 0) return *a + f(a+1, n-1); else return *a - f(a+1, n-1); } int main() { int a[] = {12, 7, 13, 4, 11, 6}; printf("%d", f(a, 6)); getchar(); return 0; } |
chevron_right
filter_none
(A) -9
(B) 5
(C) 15
(D) 19
Answer: (C)
Explanation: f() is a recursive function which adds f(a+1, n-1) to *a if *a is even. If *a is odd then f() subtracts f(a+1, n-1) from *a. See below recursion tree for execution of f(a, 6).
.
f(add(12), 6) /*Since 12 is first element. a contains address of 12 */
|
|
12 + f(add(7), 5) /* Since 7 is the next element, a+1 contains address of 7 */
|
|
7 - f(add(13), 4)
|
|
13 - f(add(4), 3)
|
|
4 + f(add(11), 2)
|
|
11 - f(add(6), 1)
|
|
6 + 0
So, the final returned value is 12 + (7 – (13 – (4 + (11 – (6 + 0))))) = 15
Quiz of this Question
Recommended Posts:
- GATE | GATE CS 2010 | Question 29
- GATE | GATE CS 2010 | Question 20
- GATE | GATE CS 2010 | Question 19
- GATE | GATE CS 2010 | Question 18
- GATE | GATE CS 2010 | Question 65
- GATE | GATE CS 2010 | Question 16
- GATE | GATE CS 2010 | Question 15
- GATE | GATE CS 2010 | Question 21
- GATE | GATE CS 2010 | Question 28
- GATE | GATE CS 2010 | Question 27
- GATE | GATE CS 2010 | Question 26
- GATE | GATE CS 2010 | Question 65
- GATE | GATE CS 2010 | Question 24
- GATE | GATE CS 2010 | Question 23
- GATE | GATE CS 2010 | Question 22



