Study the following program: // precondition: x>=0 public void demo(int x) {…

2007

Study the following program:

// precondition: x>=0
public void demo(int x)
{
    System.out.print(x % 10);
    if (x % 10 != 0) {
        demo(x / 10);
    }
    System.out.print(x % 10);
}

Which of the following is printed as a result of the call demo(1234)?

  1. A.

    1441

  2. B.

    3443

  3. C.

    12344321

  4. D.

    4321001234

Attempted by 48 students.

Show answer & explanation

Correct answer: D

The function demo(x) is a recursive method that prints the last digit of x, calls itself with x divided by 10 (removing the last digit), and then prints the last digit again after returning. For demo(1234): First, it prints 4 (1234 % 10). Since 4!= 0, it calls demo(123). Inside demo(123), it prints 3, then calls demo(12). Inside demo(12), it prints 2, then calls demo(1). Inside demo(1), it prints 1, then calls demo(0). In demo(0), it prints 0. Since 0 % 10 == 0, the recursion stops and does not call demo(0) again. As each function returns, it prints its last digit again: 1 (from demo(1)), then 2 (from demo(12)), then 3 (from demo(123)), and finally 4 (from demo(1234)). The complete output sequence is 4, 3, 2, 1, 0, 0, 1, 2, 3, 4. Thus, the correct answer is D.

Explore the full course: Isro