So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
The problem is that i cant/know how to change this into a recursive method Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.
Short, recursive and does the job:
int getsum(int n) {
return n == 0 ? 0 : n % 10 + getsum(n/10);
}
Here it is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of the function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With