Sum of all the natural numbers up to n.
Adding n before recursive call gives out 15 and adding it after the recursive call shows 10.
public static int SumThem(int n){
if(n==0){
return n;
}
return SumThem(--n) + n;
}
public static void main(String[] args){
int x = SumThem(5);
System.out.println(x);
}
Output: 10.
The output is 10 which means, while returning, the value for n=5 is not evaluated in the return statement. It only works up to n=4, but as soon as the n is added before the recursive call it works fine.
public static int SumThem(int n){
if(n==0){
return n;
}
return n + SumThem(--n);
}
public static void main(String[] args){
int x = SumThem(5);
System.out.println(x);
}
Output: 15
n=5 does count here. Why is this happening?