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)?
(A)
1441
(B)
3443
(C)
12344321
(D)
4321001234
Answer: (D)
Explanation:
In the above code, the first print statement is executed and prints the value obtained after performing a modulus of 10, and recursively another function is called with the value divided by 10. And after the return of the function, it prints the values again.
- demo(1234)
- prints 4
- call demo(123)
- prints 3
- call demo(12)
- prints 2
- call demo(1)
- prints 1
- call demo (0)
- prints 0
- prints 0
- prints 1
- prints 2
- prints 3
- prints 4.
So, option (D) is correct.
Quiz of this Question
Please comment below if you find anything wrong in the above post
Article Tags :
Recommended Articles