Hey guys in this post we will learn how to write Factorial program using iterative and recursive method approaches.
Factorial program using iterative Approach:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kkjavatutorials.client; import java.util.Scanner; public class FactorialUsingIteration { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in);) { System.out.println("Enter number for which you want to find factorial:"); int num = scanner.nextInt(); int fact = findFactorial(num); System.out.println("Factorial of "+num+" is:"+fact); } catch (Exception e) { e.printStackTrace(); } } private static int findFactorial(int num) { int fact = 1; for (int i = 2; i <= num; i++) { fact = fact*i; } return fact; } } |
Sample input & output:
1 2 3 |
Enter number for which you want to find factorial: 5 Factorial of 5 is:120 |
Factorial program recursive Approach
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.kkjavatutorials.client; import java.util.Scanner; public class FactorialUsingRecursion { public static void main(String[] args) { try(Scanner scanner = new Scanner(System.in);) { System.out.println("Enter number for which you want to find factorial:"); int num = scanner.nextInt(); int fact = findFactorial(num); System.out.println("Factorial of "+num+" is:"+fact); } catch (Exception e) { e.printStackTrace(); } } private static int findFactorial(int num) { //Base Condition if(num == 0 || num == 1) return 1; else //Recursive case return num*findFactorial(num-1); } } |
Sample input & output:
Enter number for which you want to find factorial:
4
Factorial of 4 is:24
That’s all about this topic Factorial program using iterative and recursive method If you have any doubts or any suggestions to make please drop a comment.