GATE Exam | Aptitude Questions | GATE Syllabus | GATE Result | Mock Test | GATE Preparation
0 votes

What is the value printed by the following C program?

#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;

}

(A) -9
(B) 5
(C) 15
(D) 19

asked in c programming by gate

1 Answer

0 votes
 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

answered by gate

Related questions

The best answer to any question