matcpn
matcpn

Reputation: 3

Print the return each time in a recursive statement (java)?

The project is to write a recursive method that prints the parameters and return along each step.
Here's what I have so far:

public static int summation(int lower, int upper){
    if (lower > upper)
        return 0;
    else{
        System.out.println("Current lower bound: " + lower);
        System.out.println("Upper bound: " + upper);
        return lower + summation(lower+1, upper);
    }

Its almost perfect, the only thing it's missing is printing the return every time. How do make it do that?

Upvotes: 0

Views: 1640

Answers (2)

user1247034
user1247034

Reputation:

public static int summation(int lower, int upper) {
    if (lower > upper) {
        return 0;
    } else {
        int returned = lower + summation(lower + 1, upper);
        System.out.println("Current lower bound: " + lower + " | " + "Upper bound: " + upper + " | " + "returned:" + returned);
        return returned;
    }
}

enter image description here

Upvotes: 0

aioobe
aioobe

Reputation: 421280

How about this:

public static int summation(int lower, int upper){
    if (lower > upper) {
        System.out.println("Returning: 0");               // print before return
        return 0;
    } else{
        int result = lower + summation(lower+1, upper);

        System.out.println("Current lower bound: " + lower);
        System.out.println("Upper bound: " + upper);
        System.out.println("Returning: " + result);       // print before return
        return result;
    }
}

Upvotes: 1

Related Questions