Consider a simple recursive method (Java code written by yourself or taken from
ID: 3871132 • Letter: C
Question
Consider a simple recursive method (Java code written by yourself or taken from Web) such as calculating the sum of the first n natural numbers, calculating the number of digits of an integer number, calculating 2 to the power of n, etc. Try choosing one different from that of any posted thus far.
a. Show method code, indicate what it does, identify the base case(s) and indicate how each recursive call simplifies the problem and makes progress towards the base case;
b. Provide an equivalent iterative implementation.
c. How do the two implementations compare?
Explanation / Answer
a) Recursion is used to solve complex function calls or operations in a problem. It is used to solve those problems with less and simple code with few variables and good logic. Here I am implementing factorial of a number using recursion and also using iterative method
public class MyClass {
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]) {
// Factorial using recursion method
int result = factorial(5);
System.out.println("Factorial using recursion = " + result);
}
}
**OUTPUT:
Factorial using recursion = 120
b) Equivalent iterative implementation:
public class MyClass {
public static void main(String args[]) {
// Factorial using Iteration method
int i, fact = 1;
for(i = 1 ; i <= 5 ; i++)
fact *= i;
System.out.println("Factorial using iteration = " + fact);
}
}
**Output:
Factorial using iteration = 120
C) Comparision
The recursive method is easy to solve but it slow compared to an iterative method and uses more memory for its processing as it's recursion needed to stored until the end of the program. In the above recursive method is executed until the condition in the method is satisfied. But in the iterative method just a for loop is written to execute.
**Comment for any further queries. Upvote if the answer is satisfactory.