LearnFrenzy
Sign in Take a free test

Methods and Recursion · Predict the Output · Question 17

Tracing a recursive GCD Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
public class Main {
    static int gcd(int a, int b) {
        System.out.print("(" + a + "," + b + ")");
        return b == 0 ? a : gcd(b, a % b);
    }

    public static void main(String[] args) {
        System.out.println(" = " + gcd(270, 192));
    }
}
  • A (270,192)(192,78)(78,36)(36,6)(6,0) = 6 Correct
  • B (270,192)(192,78)(78,36)(36,6) = 6
  • C (192,270)(270,192)(192,78)(78,36)(36,6)(6,0) = 6
  • D (270,192)(78,192)(36,78)(6,36)(0,6) = 6
Correct Answer: Option A

Each call prints its arguments before recursing; the chain ends when b becomes 0. The final " = " is printed after gcd returns.

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