sorry for my english
public class Exercise {
static int getAdditionalOdd(int a) {
System.out.println("iam entered "+a);
if (a <= 1)
{
System.out.println("before "+(a-2));
return 1;
}
int x = getAdditionalOdd(a -2);
System.out.println("a is "+a+" x is "+x);
System.out.println("after "+(a+x));
return a +x ;
}
static void showOddNumbers(int a) {
if (a >= 1) {
a -= 2;
showOddNumbers(a);
}
}
public static void main(String[] args) {
int number = 9;
System.out.println("Odd Numbers");
showOddNumbers(number);
System.out.println("Sum of Odds: " + getAdditionalOdd(9));
}
}
I changed programm as above for understanding purpose.
then o/p is
Odd Numbers
iam entered 9
iam entered 7
iam entered 5
iam entered 3
iam entered 1
before -1
a is 3 x is 1
after 4
a is 5 x is 4
after 9
a is 7 x is 9
after 16
a is 9 x is 16
after 25
Sum of Odds: 25
Now it is to understand bu observing output.
For first time a is 9.
now it again goes to call its own method.
for four times it goes for call its own method.
for last repetation a is 1.
for the first time when it executes return statement it returns 1. That means it came back from last repetation.
for the second time when it executes return statement it returns 4. That means it came back from lastbutone repetation.
last finally it returns 25