tejaswini venkatesh
tejaswini venkatesh

Reputation: 13

Counting numbers up and down using Recursion

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

Upvotes: 1

Views: 7122

Answers (3)

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

Upvotes: 0

Richard Buzbee
Richard Buzbee

Reputation: 1

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

Upvotes: 0

T. Claverie
T. Claverie

Reputation: 12256

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

Upvotes: 7

Related Questions