Counting numbers up and down using Recursion

后端 未结 3 1530
一个人的身影
一个人的身影 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:34

    try this

     private static int  CountUpAndDown(int end, int first, int start)
        {
            if(end==first)
            {
                return -1;
            }
            if (start > end)
            {
               System.out.println(--end);
            }
            else {
                System.out.println(start++);
            }
            return CountUpAndDown(end, first, start);
        }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-23 22:46

    You might be able to set it to a count up from 1->3 and >=4 do a -- down to 1.

    0 讨论(0)
提交回复
热议问题