Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Given two numbers, let's say start = 1 and end = 4, I am trying to count all the numbers in sequence up and then down . No looping is allowed

1 2 3 4 3 2 1

I tried writing a recursion function. The function is counting up fine and its printing 1 2 3 4 but when I try to count down, I expect 4 3 2 1 but I get into an infinite loop. The reason is the start value is lost in recursion and I don't know where to stop when counting from bottom up.

I have spent 4 hours on this . Can we even do this in recursion ? Is recursion one way

public static void countUpDown(int start, int end) {
    //to pring bottom up -> 4 3 2 1
    if ( start > end  && end > 0) {
        System.out.println(end - 1);
        countUpDown(start, end - 1);    
    }

   //to print up 1 2 3 4 
    if (start <= end) {
        System.out.println("-->" + start);
        countUpDown(start + 1, end);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
284 views
Welcome To Ask or Share your Answers For Others

1 Answer

You just have to use the recursion for counting up. Then, when the function returns, you are on your way down. This can be achieved with:

public void countUpAndDown(int start, int end) {
    System.out.println(start);
    if (end == start) return;
    countUpAndDown(start+1, end);
    System.out.println(start);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...