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


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Recursion to Print and Count

  1. #1
    Junior Member
    Join Date
    Oct 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Recursion to Print and Count

    Hi, so for an assignment I have to print out all the odd numbers between an inputed number and 0, and then print out a count of how many numbers there are, using only a recursive method (named int odd (int n). I have the printing working, I just can't seem to get the count to work. What am I doing wrong?

    public static int odds(int n) 
       {
        if (n%2==0)
        {
          n=n-1;
        }
        if (n==1)
        {
          System.out.print("");
        }
        else
        {
          System.out.print(n+" ");
          n=odds(n-2);
          count++;
        }
        return n;
      }
    Last edited by allons-y; October 22nd, 2013 at 06:13 PM. Reason: Sorry, I wrote the method down wrong. I also am only showing the method that does work, but does not print out the count.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Recursion to Print and Count

    Why didn't you show that code that almost or partly worked? I don't see any recursion here, and what is the method evens()?

  3. #3
    Junior Member
    Join Date
    Oct 2013
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Recursion to Print and Count

    Sorry, I wrote the method down wrong in the recursive statement. I am now also only showing the method that does work, but does not print out the count. I just don't understand how to print out a count of the odds.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Recursion to Print and Count

    On one hand, you're very close. On the other hand, there are some things I would do differently:

    1. Some recusive methods return a value. This one doesn't need to.
    2. The base case should be clearly defined for clarity. Your base case is defined by default and (I'm assuming) is dependent on the main() method to complete the method by printing the final odd value, 1. That's non-standard.
    3. The code can be tightened up quite a bit.

    As for maintaining and printing the number of odds, since each call to a recursive method starts that method anew, the variable count can't be declared inside the recursive method. I think you've figured that out, but we can't see where count is defined or initialized. The total count can be incremented and printed by the recursive method, however.

    This is how I would do it:
        // method odds2() prints and counts the number of odd numbers from the
        // given parameter int n to 0
        // count is a class variable
        public static void odds2( int n ) 
        {
            // the base case - stop at this condition
            if ( n <= 0 )
            {
                // print the number of odds and exit the method
                System.out.println( "The number of odds is: " + count );
                return;
            }
     
            // if n is odd, print it and count it
            if ( n % 2 != 0 )
            {
                System.out.print( n + " " );
                count++;
            }
     
            // continue to process odds until the base case
            odds2( --n );
        }

  5. #5
    Member
    Join Date
    Sep 2013
    Posts
    70
    Thanks
    1
    Thanked 13 Times in 13 Posts

    Default Re: Recursion to Print and Count

    There is one improvement I would do on your code GregBrannon as your current code executes at O(n)
     
        // method odds2() prints and counts the number of odd numbers from the
        // given parameter int n to 0
        // count is a class variable
        public static void odds2( int n ) 
        {
            // the base case - stop at this condition
            if ( n <= 0 )
            {
                // print the number of odds and exit the method
                System.out.println( "The number of odds is: " + count );
                return;
            }
     
            // if n is odd, print it and count it
            if ( n % 2 != 0 )
            {
                System.out.print( n + " " );
                count++;
                // If you are in this method you can safely say that the first odd was found.
                // When you find the first odd you can subtract by 2 and the next number is still odd.
                // This cuts down O(n) to O(n / 2) so it cuts down on how many times the method calls itself.
                odds2(n - 2);
            }
     
            // continue to process odds until the base case
            odds2( --n );
        }

    Also I agree it all depends where he declared his "count" variable. If it is declared in the main method then he will have to have a return value.

    // base case return 0
    // Odds return odds(n - 2) + 1
    // Default return odds(--n)

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Recursion to Print and Count

    Agreed. Thanks for the optimization. It had occurred to me, but I was already overstepping the bounds a bit - except the OP was sooooo close.

Similar Threads

  1. how to count and print asterisk.
    By xyldon27 in forum What's Wrong With My Code?
    Replies: 20
    Last Post: February 7th, 2013, 02:32 PM
  2. Column count doesn't match value count at row 1
    By Tyluur in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 30th, 2012, 01:31 AM
  3. Print a string in reverse using recursion
    By ManInTheMiddle in forum Algorithms & Recursion
    Replies: 5
    Last Post: December 1st, 2012, 08:30 AM
  4. Count and Print 1 to 10 in Real Time - Help :S
    By djl1990 in forum What's Wrong With My Code?
    Replies: 9
    Last Post: November 29th, 2012, 05:26 PM
  5. Replies: 1
    Last Post: August 5th, 2012, 09:28 PM

Tags for this Thread