Reputation:
I'm having to make a recursive function that will receive a stack of "int" and output the sum of the squares of the elements in the stack. Here is what I have
public int sum_sqr_rec(Stack<Integer> stk){
int sum = 0;
for (int i=0; i<stk.size(); i++){
sum += (stk.get(i) * stk.get(i));
}
return sum;
}
Upvotes: 1
Views: 105
Reputation: 40044
Lots of ways to do this. But if you don't want to destroy the stack you can do it this way. The stack is restored during the return process.
n
is popped. This depletes the stack of numbers and keeps n
in the local call stack for later use.The square of the element is saved on the call stack of the method in k
r
is initialized for the final tally.
n
back on stk
and return the sums of the saved squares.static int sum_sqr_rec(Stack<Integer> stk) {
int n = stk.pop();
int k = n*n;
int r = 0;
if (!stk.isEmpty()) {
r = sum_sqr_rec(stk);
}
stk.push(n);
return r + k;
}
Using this call sequence of statements.
System.out.println(stack);
System.out.println(sum_sqr_rec(stack));
System.out.println(stack);
Results in the following
[2, 3, 4, 5]
54
[2, 3, 4, 5]
Upvotes: 0
Reputation: 79085
The most important thing you need to determine for a recursive function is when to terminate it.
The second important thing to consider is what to return when you terminate it. When you start adding numbers, you start with sum = 0
. From a recursive function, which is supposed to calculate the sum of numbers, the same value (i.e. 0
) can be returned when you terminate it. Similarly, from a recursive function, which is supposed to return the product of numbers, you can return 1
on termination.
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
static int sum_sqr_rec(Stack<Integer> stk) {
if (stk.isEmpty()) {
return 0;
}
int n = stk.pop();
return n * n + sum_sqr_rec(stk);
}
}
Output:
54
Upvotes: 1
Reputation: 501
Note that I use Deque interface rather than Stack class directly (documentation says it should be used in preference to the Stack class).
public int recursive(Deque<Integer> stk){
if (stk.Empty()){
return 0;
}
return Math.pow(stack.pop(), 2) + recursive(stk);
}
Upvotes: 0
Reputation: 4857
You can use recursion like this:
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.add(2);
stack.add(2);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
public static int sum_sqr_rec(Stack<Integer> stack) {
if (stack.isEmpty())
return 0;
return stack.peek() * stack.pop() + sum_sqr_rec(stack);
}
Upvotes: 0