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
CodePudding user response:
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.
CodePudding user response:
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);
}