Hello, this is a simple JAVA question.Recently I m learning about Recursive Meth
ID: 3804496 • Letter: H
Question
Hello, this is a simple JAVA question.Recently I m learning about Recursive Method.
Can you show me how to use recusive method to :
1. Calculate the factorial of several numbers.(eg.from 1 to 5, answer is 120)
One of the question offer like :
public class RecursionTester {
public static void main(String[]args) {
System.out.println("Multiplication of 1 to 5: " + multiply(5));
What should I fill here? I don't need create a new class?
2.Can you introduce me how to calculate power by recursive method.
Thank you very much!!!
Explanation / Answer
public class FactorialInJava{
public static void main(String args[]) {
System.out.println("factorial of 5 using recursion in Java is: " + factorial(5));
System.out.println("factorial of 6 using iteration in Java is: " + fact(6));
}
public static int factorial(int number){
if(number == 0){
return 1;
}
return number*factorial(number -1);
}
public static int fact(int number){
int result = 1;
while(number != 0){
result = result*number;
number--;
}
return result;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.