开发者

Recursive Number Printing

If the number 5 is given to us, it needs to be printed out on the console like 1, 2, 3, 4, 5. This needs to be done recursively. (Java preferably)

In case anyone is wondering these are not homework questions. I am practicing for my midterm a week from now.

Sorry about not posting my work. I was doing something like the below: but getting confused with where to print the rest of the number, and how to stop recursively calling the method with (n - 1). Jacob with his post helped me out. Thanks to everyone who helped.

public void开发者_如何学JAVA writeNums(int n) {
    if (n < 1)
        throw new IllegalArgumentException();
    if (n == 1) {
        System.out.print("1, ");
    }
    writeNums(n - 1);


We're not going to write your code for you, but the way recursion works is that you have a function that calls itself, passing in some parameter that changes for each call. It needs to handle the "base case" in which the function does something but doesn't need to call itself anymore, and also handle the "general case" where the function both does something and calls itself to complete whatever needs to be done. So:

function printNumbersUpTo( current )
    if current is 1, print 1 and return. //base case
    otherwise, call printNumbersUpTo( current - 1), then print current, and return. //general case


Lets start by writing a function that doesn't do much but it is some obvious skeleton for basic recursive function

void Print(int num)
{
    if (num <= 0)
        return;

    Print(num - 1);
}

Now try to think where to add the atual print to console in order for the number to appear in the correct order.


If you struggled with this problem, you probably want to review how recursion in general works: http://en.wikipedia.org/wiki/Recursion_%28computer_science%29

Think about how the base case should be handled, and think about how the general case should be handled. When done right it often it can feel remarkably simple.


private static String Print(int num) {
    if (num <= 1) // base case
        return Integer.toString(num);
    else
        return Print(num - 1) + ", " + num;
    }
}


you can achive it very simply, no such special logic only thing is you have to decide printing machanism which one to print first , go through my code you will be able to understand

public static void print(int n) {
        if (n <= 0) {
            return;
        }

        print(n - 1);
        System.out.print(n+ " ");
    }

Input : 5 output : 1,2,3,4,5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜