Results 1 to 3 of 3
  1. #1
    katiebear128 is offline Member
    Join Date
    Sep 2011
    Posts
    54
    Rep Power
    0

    Default recursion problem

    Java Code:
    public static void recur2 (int n)
    {
      if(n<=0)
      { 
        return;
      }
      else
      {
        recur2(n - 2);
        System.out.print(n);
      }
    }
    My problem: What does recur2(5) display?

    I tried putting the method into a class w/ a main method like so:

    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 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?

    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?

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default Re: recursion problem

    You don't need to print the method, just call it.
    Java Code:
    public static void main(String[] args){
      //call method
    }

  3. #3
    katiebear128 is offline Member
    Join Date
    Sep 2011
    Posts
    54
    Rep Power
    0

    Default Re: recursion problem

    thanks for pointing that out! I got it :)

Similar Threads

  1. recursion problem
    By Yakg in forum New To Java
    Replies: 2
    Last Post: 01-05-2011, 03:45 PM
  2. Problem with case - might need recursion
    By Angelar in forum New To Java
    Replies: 6
    Last Post: 10-13-2010, 03:25 PM
  3. Recursion problem
    By luke in forum New To Java
    Replies: 6
    Last Post: 10-06-2010, 07:35 AM
  4. recursion and call stack problem
    By OptimusPrime in forum New To Java
    Replies: 4
    Last Post: 12-26-2009, 10:49 PM
  5. Java Recursion Problem
    By gmnnn in forum Threads and Synchronization
    Replies: 1
    Last Post: 12-06-2009, 05:22 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •