Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## 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?
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

2. ## Re: Recursion Trace

What output are you expecting?

3. ## 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:
System.out.println("in odd, number is " + number);

4. ## 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.

5. ## Re: Recursion Trace

Originally Posted by rossums
I dont believe this is a recursive method.
Yes it is a recusive method. Do you see else clause?
return (2 * number - 1) + odd(number - 1); << recursive call right there!