# Please Explain me how i got this output.. I am new to java .. so please Explain me...

• December 13th, 2010, 01:22 AM
vicky82
Please Explain me how i got this output.. I am new to java .. so please Explain me...
Code Java:

public class Exercise {
if (a <= 1)
return 1;
return a  +x ;
}
static void showOddNumbers(int a)    {
if (a >= 1) {
System.out.println(a);
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(number));
}
}

OUTPUT:
Odd Numbers : 9 7 3 2 1
Sum of Odds: 25

Can any one please explain me how i got the output 25.. its confusing for me
• December 13th, 2010, 04:13 AM
SANDEEPREDDY.PUTTA
Re: Please Explain me how i got this output.. I am new to java .. so please Explain m
sorry for my english
Code Java:

public class Exercise {

System.out.println("iam entered "+a);

if (a <= 1)
{
System.out.println("before "+(a-2));
return 1;

}

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