I need to create a print statement as "n" is being popped from the stack, just like I have one for when it is being pushed on to the stack. I understand what is happening on that final return when in the base case, but I don't know how to show the items being popped, how would I do this? Thanks in advance.
/**
*
* @author harryluthi
* @assignment 3
* @precoditions none
*
* SumOfSquares will calculate and return the sum of squares
* while also telling the user know when an item is pushed
* and popped from the stack.
*
*/
public class SumOfSquares {
private static int square;
public static int ss(int n) {
if (n == 0) {
System.out.println("Base case: n = 0");
System.out.print("Sum of squares is "+square);
return square;
}
else {
while (n > 0) {
System.out.println("Pushing call onto stack. n = " + n);
square = n*n + square;
return square + ss(n-1);
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ss(4);
}
}
Here is the console display after code runs, followed by what I need it to ultimately display.
Pushing call onto stack. n = 4
Pushing call onto stack. n = 3
Pushing call onto stack. n = 2
Pushing call onto stack. n = 1
Base case: n = 0
Sum of squares is 30
Need:
Pushing call onto stack. n = 4
Pushing call onto stack. n = 3
Pushing call onto stack. n = 2
Pushing call onto stack. n = 1
Base case: n = 0
Popping previous call from stack. n = 1
Popping previous call from stack. n = 2
Popping previous call from stack. n = 3
Popping previous call from stack. n = 4
Sum of squares is 30