top of page
Click here to go to the home page of AskTheCode.

Java Program to find Factorial of a number - Ask The Code

Team ATC

Updated: Mar 9, 2021

Find factorial of a number in Java | Java Programming Solutions | AskTheCode

 

Problem:

Write a Java program to get the factorial of a number given by the user.

For those of you who may not now, a factorial is a product of multiplying from 1 until the number. Now, you must make a program that will accept an integer and then print out its factorial using loops.


Input Sample:

5


Output Sample:

120


Explanation:

There can be different approaches to solve this problem. You can solve this question by using loop, or a function. In both cases, the process could be keep multiplying the terms up to that number given by the user. For example, if the user give input as 5, the the process should be like 1*2*3*4*5, which is equal to 120.

Let's see the two different ways to deal with this problem.


Approach I : Using a loop to get the factorial.


Code:

import java.util.Scanner;

class Factorial{
	public static void main(String arg[]){
        long fact = 1;
	
	    Scanner sc=new Scanner(System.in);
        long n = sc.nextLong();
 
	    for(int i = 1;i <= n; i++){
	    	fact = fact * i;
 	    }
  	    System.out.println(fact);
	}
}
 

Approach II : Using a recursive function


Code:

import java.util.Scanner;

public class Factorial{
	public static void main(String[] args) {
		Scanner console = new Scanner(System.in);

		int n = console.nextInt();
		int result = fact(n);
		System.out.print(result);
	}
	public static int fact(int n){
		if (n == 1){
			return n * 1;
		}
		return n * fact(n - 1);
	}
}

Recent Posts

See All

Comentários


bottom of page