What will be the output of the code given below?

public class Tester {
	public static void main(String[] args) {
		System.out.println(demo(5, 1));
	}

	public static int demo(int x, int y) {
		if (x == 0)
			return 1;
		else if (y > x)
			return 0;
		else
			return (y + demo(x - 1, y + 1));
	}
}

6

0

15

18

Verified Answer
Correct Option - a
Anush said

The output of the code will be 6. Here's the explanation:
1. The function demo(x, y) is a recursive method that follows these conditions:

  • If x == 0, it returns 1.
  • If y > x, it returns 0.
  • Otherwise, it returns y + demo(x - 1, y + 1).
2. Initially, demo(5, 1) is called, and the recursion continues until x == 0. 3. Here are the steps of the recursion:
  • demo(5, 1): returns 1 + demo(4, 2)
  • demo(4, 2): returns 2 + demo(3, 3)
  • demo(3, 3): returns 3 + demo(2, 4)
  • demo(2, 4): returns 0 because y > x
4. The final calculation is: 1 + 2 + 3 = 6.

To get all Self Assessment - Programming using Java Exam questions Join Telegram Group https://rebrand.ly/lex-telegram-236dee

Telegram

We're passionate about offering best placement materials and courses!! A one stop place for Placement Materials. We daily post Offcampus updates and Placement Materials.

Qtr No. 213, New Town Yehlanka Indore 454775

admin@prepflix.in

Updated on Mon, 8 Dec 2025