Reputation: 3
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
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;
}
}
Upvotes: 0
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