How To Create A Factorial Program In Java


Factorial programs in java: Factorial of a number is the product of all the integers from 1 to that number. For example factorial of 4 is 24.

Factorial of a number is calculated by multiplying it with all the numbers below it starting from 1. For example factorial of 4 is 4*3*2*1.

Factorial of 0 (zero) is always 1

Factorial of a negative number doesn’t exist.

In this post I will show you how to create a Factorial program in Java using recursion and without using recursion.

In this blog, we are going to learn how to create a factorial program in Java.

What is a Factorial Program?

A factorial number is a product of all positive descending integers. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. And the factorial of 3 (denoted as 3!) is 1*2*3 = 6. The factorial of 0! is 1.

We can create a function to calculate the factorial program in Java. It is given below:

public class FactorialProgram {

public static void main(String[] args) {

int n = 5; //Initialize a number, here it is 5

int result = 1; //Initialize a result to hold the factorial value later on

for(int i=1; i<=n; i++) { //Loop through each number from 1 to n, i.e. from 1 to 5 in this case result = result * i; //Multiply each number with the previous result value, i.e. result = 1*1, then result = 2*1, then result = 6* This tutorial will show you how to write a factorial program in Java. It is an example of a recursive function as it calls itself during its execution. First, let's define what a factorial is! The mathematical definition is: n! = n × (n-1) × (n-2) ×……× 3 × 2 × 1 So, 3! = 3 x 2 x 1 = 6 and 5! = 5 x 4 x 3 x 2 x 1 = 120. You can see that the value increases quite rapidly as the number gets bigger! Now, let's look at an example of how to write a factorial program in Java. import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner reader = new Scanner(System.in); int fact = 1, n; System.out.println("Enter a number: "); n = reader.nextInt(); for (int i = 1; i<=n; i++) { fact *= i; } System.out.println("Factorial of " + n + " is: " + fact); } } import java.util.Scanner; public class Factorial { public static void main(String args[]){ int i,n,fact=1; System.out.println("Enter the number"); Scanner sc=new Scanner(System.in); n=sc.nextInt(); for(i=1;i<=n;i++) fact=fact*i; System.out.println("Factorial is"+fact); } } public class Factorial { public static void main(String[] args) { // TODO Auto-generated method stub int result=1; int number=5; for(int i=1;i<=number;i++) { result=result*i;} System.out.println("Factorial of a number is "+result); } } import java.util.*; public class MyClass { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int f=1; for(int i=1;i<=n;i++) f*=i; System.out.println(f); } }


Leave a Reply

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