This document presents a Java program that calculates the factorial of a number using recursion. It prompts the user to enter a number and then computes the factorial through a recursive method. The program outputs the result to the console.
import java.util.Scanner;public class Factorial { method usi.pdf
1. import java.util.Scanner;
public class Factorial
{
// method using recursion to find factorial of number
public static int factorial(int input)
{
// factorial of 0 is 1
if (input == 0)
{
return 1;
}
// else recursively call the function
else
{
return input * factorial(input - 1);
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int input;
System.out.println("Enter a number: ");
input = scan.nextInt();
// store result in answer
int answer = factorial(input);
System.out.println("The factorial of " + input + " is " + answer);
}
}
Solution
import java.util.Scanner;
public class Factorial
{
2. // method using recursion to find factorial of number
public static int factorial(int input)
{
// factorial of 0 is 1
if (input == 0)
{
return 1;
}
// else recursively call the function
else
{
return input * factorial(input - 1);
}
}
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int input;
System.out.println("Enter a number: ");
input = scan.nextInt();
// store result in answer
int answer = factorial(input);
System.out.println("The factorial of " + input + " is " + answer);
}
}