ProgrammingVery hardProduct company OA · GATE CS

With a C99 (or later) compiler, what is printed?

With a C99 (or later) compiler, what is printed?
int ds(int n) { return n == 0 ? 0 : n % 10 + ds(n / 10); }
int main(void) { printf("%d", ds(-123) + ds(45)); }
  1. A. 3
  2. B. 9
  3. C. Nothing: the recursion never ends
  4. D. 15

Correct answer: A. 3

C99 division truncates toward zero, so -123 / 10 = -12 and -123 % 10 = -3: the digits come out as -3, -2, -1, summing to -6, and n still reaches 0. Adding ds(45) = 9 gives 3. '15' assumes the digits are positive; endless recursion is what floor division (as in Python) would cause.

More C Programming questions

Exams that ask this topic