Knowee
Questions
Features
Study Tools

Select the correct answerWhat will be the output of the following Java program?class recursion   {    int fact(int n)     {      int result;      if (n == 1)        return 1;      result = fact(n - 1) * n;      return result;    }  }   class Output   {    public static void main(String args[])     {      recursion obj = new recursion() ;      System.out.print(obj.fact(5));    }  }Options12030 24 720

Question

Select the correct answerWhat will be the output of the following Java program?class recursion   {    int fact(int n)     {      int result;      if (n == 1)        return 1;      result = fact(n - 1) * n;      return result;    }  }   class Output   {    public static void main(String args[])     {      recursion obj = new recursion() ;      System.out.print(obj.fact(5));    }  }Options12030 24 720

...expand
🧐 Not the exact question you are looking for?Go ask a question

Solution

The correct answer is 120.

Here's the step by step explanation:

The main method calls the fact method with 5 as an argument.

In the fact method, it checks if n is equal to 1. If it is, it returns 1. If it's not, it calls fact with n-1 (which is 4 in the first call) and multiplies the result by n (which is 5 in the first call).

This process continues until n is equal to 1.

So the calculation goes like this:

5 * fact(4) 5 * (4 * fact(3)) 5 * (4 * (3 * fact(2))) 5 * (4 * (3 * (2 * fact(1)))) 5 * (4 * (3 * (2 * 1)))

When you calculate this, the result is 120.

This problem has been solved

Similar Questions

Select the correct answerWhat will be the output of the following Java programclass recursion { int func (int n) { int result; result = func (n - 1); return result; } } class Output { public static void main(String args[]) { recursion obj = new recursion() ; System.out.print(obj.func(12)); } }OptionsCompilation Error10Runtime Error

the correct answerWhat is Recursion in Java?

Select the correct answer What will be the output of the following Java code?class evaluate {  public static void main(String args[])     {   int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};   int n = 8;      n = arr[arr[n] / 4];   System.out.println(arr[n] / 4);    } }Options1230

What will be the output of the following code ?public static void print(int n){ if(n < 0){ return; } if(n == 0){ System.out.println(n); return; } print(n--); System.out.print(n+" ");}public static void main(String[] args) { int num = 3; print(num);

Select the correct answerWhat will be the output of the following Java program?class java   {    public static void main(String args[])    {      int var1 = 3;       int var2 = 8;      if ((var2 = 2) == var1)        System.out.print(var2);      else         System.out.print(++var2);    }   }Options4213

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.