Open In App

C Language | Set 8

Improve
Improve
Like Article
Like
Save
Share
Report

Following questions have been asked in GATE CS 2011 exam.

1) What does the following fragment of C-program print?




char c[] = "GATE2011";
char *p =c;
printf("%s", p + p[3] - p[1]) ;


(A) GATE2011
(B) E2011
(C) 2011
(D) 011

Answer: (C)
See comments for explanation.




char c[] = "GATE2011";
 
 // p now has the base address string "GATE2011"
char *p =c; 
 
// p[3] is 'E' and p[1] is 'A'.  
// p[3] - p[1] = ASCII value of 'E' - ASCII value of 'A' = 4
// So the expression  p + p[3] - p[1] becomes p + 4 which is 
// base address of string "2011"
printf("%s", p + p[3] - p[1]) ; 




2) Consider the following recursive C function that takes two arguments




unsigned int foo(unsigned int n, unsigned int r) {
  if (n  > 0) return (n%r +  foo (n/r, r ));
  else return 0;
}


What is the return value of the function foo when it is called as foo(513, 2)?
(A) 9
(B) 8
(C) 5
(D) 2

Answer: (D)
foo(513, 2) will return 1 + foo(256, 2). All subsequent recursive calls (including foo(256, 2)) will return 0 + foo(n/2, 2) except the last call foo(1, 2) . The last call foo(1, 2) returns 1. So, the value returned by foo(513, 2) is 1 + 0 + 0…. + 0 + 1.
The function foo(n, 2) basically returns sum of bits (or count of set bits) in the number n.


3) What is the return value of the function foo when it is called as foo(345, 10) ?

(A) 345
(B) 12
(C) 5
(D) 3

Answer: (B)
The call foo(345, 10) returns sum of decimal digits (because r is 10) in the number n. Sum of digits for 345 is 3 + 4 + 5 = 12.

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.



Last Updated : 13 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads