I want to calculate the power of 2 using recursion. Here is my code:
class Aufg1{
public static void main(String args[]){
int erg = zweiHochPositiv(10);
}
public static int zweiHochPositiv(int exponent){
if(exponent > 0)
return (2*zweiHochPositiv(exponent--));
else
return 1;
}
}
I get a lot of errors at
return (2*zweiHochPositiv(exponent--));
but I have no idea what may be wrong.
Replace
with
exponent--evaluates to the value of theexponentvariable and then decrements it. So when you callzweiHochPositiv(1), the method will callzweiHochPositiv(1)again.As a result, this method, when called with a value > 0, will recurse indefinitely and ultimately overflow the stack.