Question

Consider the following C code snippet designed to calculate the sum of digits of a non-negative integer:     #include     int sumDigits(int
n) {         if (n == 0) {             return 0;         }         // Error in recursive step         return sumDigits(n / 10);     }     int main() {         printf("%d\n", sumDigits(123));         return 0;     }     What is the error in the sumDigits function above, and how should it be corrected to correctly calculate the sum of digits of a non-negative integer?

A The base case n == 0 is incorrect; it should be n < 10.
B The recursive step sumDigits(n / 10) is missing the addition of n % 10.
C The function will cause a stack overflow for n > 0.
D The function should return n for n < 10 in the base case.
E The function is correct as is.
Practice Next

Hey! Ask a query