Arefe
Arefe

Reputation: 1059

Print forward sequencing followed by backward sequencing till the beginning?

I have an interesting problem to solve where I have given start and end integer values and I will need to print from start to end and then from end to start using recursion.

for example -

start = 2 and end = 5 then the method should print the following,

2,3,4,5,4,3,2

I can easily do the first part using the code,

public static void countUp(int start, int end) {    

    System.out.println(start);

    if(start< end){

        countUp(start+1, end);
    }
}

But, then the start value is increased within recursion and I don't have a way to find where to decrease. How can I improve my code mentioning only one method is allowed to use ? Currently, It's only printing

2,3,4,5 // I don't care about the commas  

Upvotes: 0

Views: 340

Answers (3)

roottraveller
roottraveller

Reputation: 8242

try this,

public static void countUp(int start, int end) {    

 System.out.println(start);

  if(start< end){

     countUp(start+1, end);
     System.out.println(start); //backtracking

   }
}

Upvotes: 6

Arefe
Arefe

Reputation: 1059

The solution of the problem only with recursion is as following,

public static void countUp(int start, int end) {    

    System.out.println(start);

    if( start< end){

        countUp(start+1, end);
    }

    if( start != end){

        System.out.println(start);
    }
}

Upvotes: 0

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 38000

countUp(start+1, end); doesn't increase start - it computes start+1 and passes the result to a new invocation of countUp, which will have its own value of start. Inside the current invocation, start still has the same value. After the recursive call has completed, control will return to the current invocation and will continue after the call. What happens if you simply print start at the end of your method?

Upvotes: 4

Related Questions