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

2007

Study the following Java 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);
}

What is printed by the call demo(1234)?

Answer: D. 4321001234ConceptIn recursion, statements before the recursive call run while the call stack grows, and statements after it run while the stack unwinds. Integer…

  1. A.

    1441

  2. B.

    3443

  3. C.

    12344321

  4. D.

    4321001234

Attempted by 123 students.

Show answer & explanation

Correct answer: D

Concept

In recursion, statements before the recursive call run while the call stack grows, and statements after it run while the stack unwinds.

Integer division by 10 removes the last decimal digit, while remainder modulo 10 reads that digit.

Application

  1. demo(1234) prints 4, then calls demo(123) because 4 is nonzero.

  2. demo(123), demo(12), and demo(1) print 3, 2, and 1 respectively; each then calls the method with its last digit removed.

  3. demo(0) prints 0. Its remainder is 0, so it makes no further recursive call, and its final print statement prints 0 again.

  4. The stack then unwinds: demo(1), demo(12), demo(123), and demo(1234) print 1, 2, 3, and 4 respectively.

  5. Combining the growing-stack and unwinding phases gives 4 3 2 1 0 0 1 2 3 4, so the output is 4321001234.

Cross-check

There are five calls, for x = 1234, 123, 12, 1, and 0. Every call executes two print statements, so ten digits must appear; 4321001234 has exactly ten digits and mirrors the call sequence around the two zeros printed by demo(0).

Explore the full course: Rssb Senior Computer Instructor

Loading lesson…