Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

How to Find Factorial of a given number using recursion in Java?

$
0
0
How to Find a Factorial of a given number using recursion in Java?

What is a factorial number?

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

Here is a simple program for:

  • Write a program in java to calculate factorial with output.
  • Recursive Programming Java
  • Factorial Calculator n!
  • Program for factorial of a number

Create class CrunchifyFactorialNumber.java

package crunchify.com.java.tutorials;

import java.util.Scanner;

public class CrunchifyFactorialNumber {
	public static void main(String[] args) {
		
		// Let's prompt user to enter number
		
		// A simple text scanner which can parse primitive types and strings using regular expressions.
		//A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
		// The resulting tokens may then be converted into values of different types using the various next methods.
		Scanner crunchifyScan = new Scanner(System.in);
		
		crunchifyPrint("Enter the number:");
		int crunchifyNumber = crunchifyScan.nextInt();
		crunchifyPrint("\n");
		int crunchifyFactorialNumber = crunchifyFactorial(crunchifyNumber);
		crunchifyPrint("1" + "\n\n");
		crunchifyPrint("==> Here you go: Factorial of number " + crunchifyNumber + " is: " + crunchifyFactorialNumber);
	}
	
	// Simple Print method
	private static void crunchifyPrint(String s) {
		System.out.print(s);
	}
	
	static int crunchifyFactorial(int number) {
		int crunchifyResult;
		if (number == 1) {
			return 1;
		}
		// Here you go recursion!
		crunchifyPrint(number + " x ");
		crunchifyResult = crunchifyFactorial(number - 1) * number;
		//crunchifyPrint ("1" + "\n\n");
		
		return crunchifyResult;
	}
}

Just run above program as a Java program and you will result like this:

Write a program to find factorial number

Eclipse console result:

Enter the number: 7

7 x 6 x 5 x 4 x 3 x 2 x 1

==> Here you go: Factorial of number 7 is: 5040
Process finished with exit code 0
Enter the number: 15

15 x 14 x 13 x 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1

==> Here you go: Factorial of number 15 is: 2004310016
Enter the number: 10

10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1

==> Here you go: Factorial of number 10 is: 3628800

Let us know if you face any issue running this in your eclipse console or IntelliJ IDEA.

What is Factorial?

The post How to Find Factorial of a given number using recursion in Java? appeared first on Crunchify.


Viewing all articles
Browse latest Browse all 1037

Trending Articles