📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    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. Correct Answer Incorrect Answer
    B The recursive step sumDigits(n / 10) is missing the addition of n % 10. Correct Answer Incorrect Answer
    C The function will cause a stack overflow for n > 0. Correct Answer Incorrect Answer
    D The function should return n for n < 10 in the base case. Correct Answer Incorrect Answer
    E The function is correct as is. Correct Answer Incorrect Answer

    Solution

    The current implementation of sumDigits(n) for n > 0 simply calls sumDigits(n / 10). This means it effectively truncates the last digit (n % 10) and only processes the remaining digits. For example, sumDigits(123) would call sumDigits(12), then sumDigits(1), then sumDigits(0), which returns 0. The final output would be 0, which is incorrect. To correctly sum the digits, the current digit (n % 10) must be added to the sum of the remaining digits. The corrected recursive step should be return (n % 10) + sumDigits(n / 10);.

    Practice Next
    ask-question