Study the following programme // precondition : x >= 0 public void demo(int x)…
2007
Study the following programme
// 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)?
- A.
1441
- B.
3443
- C.
12344321
- D.
43211234
Attempted by 127 students.
Show answer & explanation
Correct answer: D
The first print outputs the last digit before the recursive call, so 1234 prints 4, then 3, then 2, then 1.
When the recursion returns, each call prints its last digit again in reverse return order: 1, 2, 3, 4.
Therefore the complete output is 43211234.