Recursion – Finding Factorial

Recursive
import java.util.Scanner;

public class Factorial {
	public static void main(String args[]) {
		System.out.println("Enter a number :");
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		System.out.println("Factorial of " + x + " is : " + factorial(x));
	}

	public static int factorial(int x) {
		if (x == 0 || x == 1) {
			return 1;
		} else {
			return x * factorial(x - 1);
		}
	}
}

Iterative

import java.util.Scanner;

public class IterativeFactorial {
	public static void main(String args[]){
		System.out.println("Enter a number :");
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		System.out.println("Factorial of " + x + " is : " + factorial(x));
	}
	public static int factorial(int x){
		int product=1;
		if (x == 0 || x == 1) {
			return product;
		}else{
			for(int i=1;i<=x;i++){
				product=product*i;
			}
			return product;
		}
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *