3

I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five. 1 + 2 + 3 + 4 + 5 = 15

The current code always returns 0, how can the amount each time the n?

public class t {
public static void main(String[] args) {

    System.out.println(num(5));
}

public static int num(int n) {

    int sum = 0;
    sum += n;
    if (n == 0)
        return sum;

    return num(n - 1);

}

}

thank you.

2
  • 2
    Try use a pen or debug. Commented Jun 4, 2016 at 9:12
  • 1
    You only use the sum when n == 0, otherwise you ignore it. Commented Jun 4, 2016 at 10:15

3 Answers 3

6

Instead of setting the sum to 0 you can -
Do this:

public int sumUp(int n){

    if (n==1)
        return 1;
    else
       return sumUp(n-1)+n;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@KevinWallis and that's not even all you can do. return n <= 1 ? n : num(n -1) + n; does it in 1 line.
he just seems to be .. learning java ; why do you wanna confuse him with that anyways, i'll add it to my answer..
2

The problem is you set the sum always 0.

public static void main(String[] args) {
    System.out.println(num(5, 0));
}

public static int num(int n, int sum) {
    if (n == 0) {
        return sum;
    }

    sum += n;
    return num(n - 1, sum);

}

Comments

2
public static int withRecursion(List<Integer> list) {

    int size = list.size();
    int a=0;

    if(list.isEmpty() == true) {
        return 0;

    }else {
        a = a + list.get(0) + withRecursion(list.subList(1, size)); 
        return  a;      
    }   

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.