C Language | Set 7
Following questions have been asked in GATE CS 2010 exam.
1. What does the following program print?
#include<stdio.h> 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
Answer (D)
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<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
Answer (C)
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
Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
Please Login to comment...