Counting numbers up and down using Recursion

后端 未结 3 1533
一个人的身影
一个人的身影 2021-01-23 22:12

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

3条回答
  •  遥遥无期
    2021-01-23 22:44

    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);
    }
    

提交回复
热议问题