Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
Recursive digits sum without the right digit

I need to write a recursive function that will sum all the digits of the given number exept of the most right digit. For example: 56643 -> 5 + 6 + 6 + 4 = 21

Or if the number is 5: the sum will be 0 because we will not sum the right digit (in this example its also our only digit).

I tried to write the recursive function, but without success.

int sumDig(int num) {
    if (num < 10)
        return 0;
    return (num % 10 + sumDig(num / 10));
}

Thanks for everyone

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The function you have written would print the sum of all digits of num except the first digit, which is the opposite of what you want to achieve. Consider the following function:-

    int sumDig(int num) {
        if (num > 0)
            return (num % 10 + sumDig(num / 10));
        else
            return 0;
    }

You can directly call this function with num/10 to achieve your use case. Alternatively, you can use a wrapper function.

over 4 years ago · Santiago Trujillo Report

0

Because the base case is num<10, you're actually adding all except the most significant digit.

To get all except the last, this can be done by having the function grab the second-to-last digit and adding that to the result of the recursive call.

int sumDig(int num) {
    if (num == 0) {
        return 0;
    }
    return ((num / 10) % 10) + sumDig(num / 10);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!