LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 6

Printing before and after a recursive call Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following Java program?

Main.java
public class Main {
    static void f(int n) {
        if (n == 0) return;
        System.out.print(n + " ");
        f(n - 1);
        System.out.print(n + " ");
    }

    public static void main(String[] args) {
        f(3);
        System.out.println();
    }
}
  • A 3 2 1 1 2 3 Correct
  • B 3 2 1
  • C 1 2 3 3 2 1
  • D 3 2 1 3 2 1
Correct Answer: Option A

Prints before the call happen on the way down; prints after the call happen on the way back up, in reverse order.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links