Java Code: Write a java program to calculate the factorial of a number using recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public static int factorial (int number) { if(number > 1) { return number * factorial(number-1); } return number; } public static void main(String[] args) { int num = 5; System.out.printf("Factorial of %d = %d \n", num, factorial(5)); } |
Java Code: Write a java program to calculate the factorial of a given number by user using recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public static int factorial (int number) { if(number > 1) { return number * factorial(number-1); } return number; } public static void main(String[] args) { // input from standard input - keyboard Scanner reader = new Scanner(System.in); System.out.print("Enter a Number: "); // nextInt() reads the next integer from the keyboard int num = reader.nextInt(); System.out.printf("Factorial of %d = %d \n", num, factorial(5)); } |
Output:
In this example, you have learned how to find the factorial of a number using recursive method.