Select the correct answerWhat will be the output of the following Java program? class recursion { int func (int n) { int result; if (n == 1) return 1; result = func (n - 1); return result; } } class Output { public static void main(String args[]) { recursion obj = new recursion() ; System.out.print(obj.func(5)); } }Options 12010None of the mentioned
Question
Select the correct answerWhat will be the output of the following Java program? class recursion { int func (int n) { int result; if (n == 1) return 1; result = func (n - 1); return result; } } class Output { public static void main(String args[]) { recursion obj = new recursion() ; System.out.print(obj.func(5)); } }Options 12010None of the mentioned
Solution
The correct answer is 1.
Here's the step by step explanation:
-
The function
funcis a recursive function, which means it calls itself. -
The base case for this recursive function is when
nequals 1, it returns 1. -
If
nis not 1, the function calls itself withn - 1. -
This process continues until
nequals 1. -
In the
mainmethod, the functionfuncis called withnequals 5. -
The function will call itself with
nequals 4, then 3, then 2, and finally 1. -
When
nequals 1, the function returns 1. -
Therefore, the output of the program is 1.
Similar Questions
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(1)); } }Options 120301Runtime Error
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
the correct answerWhat is Recursion in Java?
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);
e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}
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.