Results 1 to 3 of 3
Thread: recursion problem
- 10-20-2011, 07:09 PM #1
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
recursion problem
My problem: What does recur2(5) display?Java Code:public static void recur2 (int n) { if(n<=0) { return; } else { recur2(n - 2); System.out.print(n); } }
I tried putting the method into a class w/ a main method like so:
But I can't put System.out.println(recur(5)) anywhere without it telling me a void statement can't go there...How can I get it to run?Java Code:public class recur2{ public static void main(String[] args){ }//end main public static void recur2 (int n) { if(n<=0) { return; } else { recur2(n - 2); System.out.print(n); } } }
But thinking it through, I know for 5 it go to the else statement first: so you get recur2(5-2);
So it prints out 5, but in the background there is 3! still going on. takes the 3! goes to else statement again get 1!, but it prints out 3. Is that logic at all right? And I don't get what the base case is...it does says return. return what?
- 10-20-2011, 07:12 PM #2
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Re: recursion problem
You don't need to print the method, just call it.
Java Code:public static void main(String[] args){ //call method }
- 10-20-2011, 07:19 PM #3
Member
- Join Date
- Sep 2011
- Posts
- 54
- Rep Power
- 0
Similar Threads
-
recursion problem
By Yakg in forum New To JavaReplies: 2Last Post: 01-05-2011, 02:45 PM -
Problem with case - might need recursion
By Angelar in forum New To JavaReplies: 6Last Post: 10-13-2010, 02:25 PM -
Recursion problem
By luke in forum New To JavaReplies: 6Last Post: 10-06-2010, 06:35 AM -
recursion and call stack problem
By OptimusPrime in forum New To JavaReplies: 4Last Post: 12-26-2009, 09:49 PM -
Java Recursion Problem
By gmnnn in forum Threads and SynchronizationReplies: 1Last Post: 12-06-2009, 04:22 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks