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?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);.
Which is the 1st state to start the MBBS (Bachelor of Medicine and Bachelor of Surgery) course in Hindi?
Which agribusiness company is planning to invest Rs 300 crore over the next 3-4 years to set up an integrated palm oil complex, including a crude palm o...
Consider the following statements with respect to the growth forecasts been projected by the World Bank -
I. The World Bank has slashed the growt...
- For which agricultural commodity has the Government of India abolished the 20 percent export duty?
- Which of these dams is NOT located in the state of Uttarakhand?
- Which European nation appointed Duro Macut as Prime Minister in April 2025?
- When was the Euro officially adopted as the common European currency?
 Who won the gold medal in the men's long jump event at the MVA High Performance 1 2023 athletics meet?
Which of the following country has recently become the 99th member of the International Solar Alliance (ISA)?Â
Which cities in India have been nominated for the Wetland City Accreditation (WCA) scheme under the Ramsar Convention, aiming to gain international reco...