GeeksforGeeks App
Open App
Browser
Continue

# C Language | Set 7

Following questions have been asked in GATE CS 2010 exam.

1. What does the following program print?

 `#include``void` `f(``int` `*p, ``int` `*q)``{``  ``p = q;`` ``*p = 2;``}``int` `i = 0, j = 1;``int` `main()``{``  ``f(&i, &j);``  ``printf``(``"%d %d \n"``, i, j);``  ``getchar``();``  ``return` `0;``}`

(A) 2 2
(B) 2 1
(C) 0 1
(D) 0 2

See below f() with comments for explanation.

 `/* p points to i and q points to j */``void` `f(``int` `*p, ``int` `*q)``{``  ``p = q;    ``/* p also points to j now */`` ``*p = 2;   ``/* Value of j is changed to 2 now */``}`

2. What is the value printed by the following C program?

 `#include``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

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 */
|
|
|
|
|
|
|
|