Reputation: 93
I have been trying to figure out why the output is 321 and not 123. I have tried multiple times and looking out lecture slides but I still can't get the solution to this question.
public static void main(String[] args) {
printNumber(1);
}
public static void printNumber(int n) {
if(n!=4) {
printNumber(n + 1);
System.out.print(n);
}
}
Upvotes: 2
Views: 132
Reputation: 2340
The reason for this result that you have placed the recursion call statement printNumber(n + 1)
before print statement System.out.print(n)
so it will keep recursivly calling it until it reach 4
after that it will print numbers from last call n+1
to n
as in our example from 3
to 1
try this :
public static void printNumber(int n) {
if(n!=4) {
System.out.print(n);
printNumber(n + 1);
}
}
you will find the output: 123
The reason for that is at each recursion call it will print the number n
then it will call it another time for n+1
until it reach 4
.
Upvotes: 0
Reputation: 59096
Each call to printNumber
calls printNumber(n+1)
first, and then prints something out. So printNumber(n+1)
has already finished before printNumber(n)
prints its number out.
main():
printNumber(1):
printNumber(2):
printNumber(3):
printNumber(4) // does nothing
print(n) // "3"
// printNumber(3) completes, returning control to printNumber(2)
print(n) // "2"
// printNumber(2) completes, returning control to printNumber(1)
print(n) // "1"
// printNumber(1) completes, returning control to main()
// main() completes
Upvotes: 7
Reputation: 8819
The variable n
is either 1 2 or 3.
What are you printing first, n
or n + 1
? You are printing n + 1
first, then n
. So the numbers must come out in reverse order.
Upvotes: 1