# Recursion Trace

• August 18th, 2011, 09:25 PM
hello_world
Recursion Trace
I have this recursion that I created the main for but cant figure out the trace as to why it provides the output it does. Can someone provide me a trace?
Code Java:

```import java.util.*;   public class oddRecurrsion{   public static void main(String[] args){   Scanner stdin = new Scanner(System.in);   System.out.print("Enter an integer: "); int input = stdin.nextInt();   System.out.println("Integer \"" + input + "\" equals " + odd(input)); } //end main   public static int odd(int number) {   if (number == 1) return 1; else return (2 * number - 1) + odd(number - 1); } //end odd   } // end class```

OUTPUT:
Enter an integer: 5
Integer "5" equals 25

Enter an integer: 3
Integer "3" equals 9
• August 18th, 2011, 10:44 PM
helloworld922
Re: Recursion Trace
What output are you expecting?
• August 19th, 2011, 04:02 AM
Sean4u
Re: Recursion Trace
One way to get your own stack traces is to instantiate an Exception in your invoked method, use yourException.fillInStackTrace() (not sure whether that's absolutely necessary or not without reading the API docs) and then yourException.printStackTrace(). Remember not to throw the Exception!

I think you'd get as meaningful information from:
Code :

`System.out.println("in odd, number is " + number);`
• August 22nd, 2011, 01:54 PM
rossums
Re: Recursion Trace
I dont believe this is a recursive method. You never actually call on itself. You need a case that ends the recursion and returns a value in addition to the method calling on itself.
• August 22nd, 2011, 10:35 PM
Junky
Re: Recursion Trace
Quote:

Originally Posted by rossums
I dont believe this is a recursive method.

Yes it is a recusive method. Do you see else clause?
Code java:

`return (2 * number - 1) + odd(number - 1); << recursive call right there!`