28.4k views
1 vote
Show the output of the following code: public class Test1 { public static void main(String[] args) { System.out.println(f2(2, 0)); } public static int f2(int n, int result) { if (n == 0) return 0; else return f2(n - 1, n + result); } }

User Tawnos
by
7.7k points

1 Answer

1 vote

Answer:

0

Step-by-step explanation:

Given the code as follows:

  1. public class Test1 {
  2. public static void main(String[] args) {
  3. System.out.println(f2(2, 0));
  4. }
  5. public static int f2(int n, int result)
  6. {
  7. if (n == 0)
  8. return 0;
  9. else
  10. return f2(n - 1, n + result);
  11. }
  12. }

The code above shows a recursive function calling (Line 11). The f2 function will call itself when n is not equal to 0. In the main program, f2 function is called by passing argument 2 and 0 to parameter n and result, respectively (Line 3).

Since the n is not equal to 0, and therefore else statement will run (Line 11). f2 function is called recursively for several rounds:

Round 1 - f2(2-1, 2 + 0) - > f2 (1, 2)

Round 2 - f2(1 -1 , 1 + 2) -> f2(0, 3)

f2(0 , 3) will return 0 and the 0 will be returned to the calling point at f2(1, 2). At the end, the same 0 value will be return from the f2 function.

User Nitz
by
6.5k points