Sat Aug 28 2021

Recursive Factorial

File Name: factorial-recursion.java

import java.io.*;
import java.util.Scanner;

class calculating {

	/* Recursive method */
	int factorial_cal(int no) {
		if(no == 1)
			return 1;
		else
			return(no * factorial_cal(no - 1));
	}
}
										
class factorial {
	public static void main(String args[ ]) {
		int f;

		/* Creating object of the Scanner */
		Scanner r = new Scanner(System.in);
		System.out.println("Program to calculate factorial");
		System.out.println("Enter a number:");

		/* Create object of 'calculating' class */
		calculating cal = new calculating();

		/* Received data from user using scanner object and pass to recursive method */
		f = cal.factorial_cal(Integer.parseInt(r.nextLine());
		System.out.println("Factorial: "+f);
	}
}




/* Output */
Program to calculate factorial
Enter a number:
5

Factorial: 120
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.