2

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);
    }
}
3
  • 2
    If you do not understand recursion read this sentence from the beginning. Commented Nov 22, 2017 at 11:29
  • Sorry, there is something wrong with the above sentence. I have been trying to figure out why the answer is 321 and not 123. Commented Nov 22, 2017 at 11:31
  • 3
    try to go through the code step by step (as you were running it) and write on a paper n when you encounter System.out.print(n) Commented Nov 22, 2017 at 11:31

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.