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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…