Search code examples
javarecursionedx

How do I count up using recursion in Java?


So, I'm auditing a Java course on EdX and have been doing really well up until this point. I've come to recursions and one of the tasks is to create a method that counts up to a specified number placing commas between each (i.e. System.out.println(writeNum(5)); should print "1, 2, 3, 4, 5, ... n" with no comma on the final number).

Additionally, there's supposed to be an IllegalArgumentException should a value less than 1 be passed.

I've been on it for 2 days wracking my brain and I cannot even comprehend how to start. I can do the factorial one :

public static int factorial (int n) {
        if(n == 1){
            return 1;
        }
        System.out.println(n);
        return n*factorial(n-1);

}

No problems right? So, thinking about it I keep thinking, what is the base case? Is it 1? if so, then I'm just counting down and somehow need to count down, reorganize them, reprint them, then somehow figure it out that way. Or, I make my base case when n==n, which doesn't work either... I know I am probably overthinking this, but I have no idea how to even get it started... If anyone could go through it with me step by step to understand this, I would sincerely be grateful as I'm doing this because I genuinely want to learn and understand this stuff.


Solution

  • For recursion, you need to find when to return e.g. in the code given below, when n == 1, the method prints the value of n and returns. Apart from the terminating condition, another important aspect is where (i.e. whether before calling the method/function recursively or after it) you process (e.g. print) the parameter.

    public class Main {
        public static void main(String[] args) {
            count(5);
        }
    
        static void count(int n) {
            if (n == 1) {
                System.out.print(n);
                return;
            }
            count(n - 1);
            System.out.print("," + n);
        }
    }
    

    Output:

    1,2,3,4,5
    

    This is how it works:

    count(5) -> calls count(4) with remaining thing to do is print ,5 once count(4) returns.
        count(4) -> calls count(3) with remaining thing to do is print ,4 once count(3) returns. 
            count(3) -> calls count(2) with remaining thing to do is print ,3 once count(2) returns.
                count(2) -> calls count(1) with remaining thing to do is print ,2 once count(1) returns. 
                    count(1) -> prints 1 and returns. 
                The remaining thing of count(2) is done i.e. ,2 is printed.
            The remaining thing of count(3) is done i.e. ,3 is printed.
        The remaining thing of count(4) is done i.e. ,4 is printed.
    The remaining thing of count(5) is done i.e. ,5 is printed.
    

    Check this to learn more about recursion.