# factorial program in java How to Solve a

// Factorial program in java How to Solve a*

public class Factorial {

public static void main(String[] args) {

int f = 1; // defining the factorial value

int num = 5; // defining the number

for (int i = 1; i <= num; i++) { f *= i; // calculating factorial value } System.out.println("Factorial is: " + f); } } Factorial program in java How to Solve a Factorial Program in Java? A factorial is represented by the sign (!). It means to multiply a series of descending natural numbers. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120. In programming we represent the factorial of a number with the help of for loop and while loop. Factorial Program in Java Using While Loop In this program, we use two variables: one stores value that is entered by user (num) and other variable (fact) stores the factorial of a number. We first read the number from user using a scanner object and stored it in variable num. Then, we used while loop to iterate until num is greater than zero according to the condition of while loop. Inside the while loop, we store the value of fact multiplied by num in fact itself. At last, we decrement num by 1. Once the while loop completes its execution, our program will print out the desired result which is stored in variable fact. public class FactorialProgram { public static void main(String[] args) { //number to calculate factorial int number = 5; long fact = 1; for(int i = 1; i <= number; i++){ fact = fact * i; } System.out.println("Factorial of "+number+" is: "+fact); } } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1;import java.util.Scanner;/** * * @author iaquino */public class Factorial{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int n = sc.nextInt(); System.out.println("The factorial of " + n + " is " + fact(n)); } public static int fact(int x) { if (x == 0) return 1; else return x*fact(x-1); }} public class FactorialExample { public static void main(String args[]) { int i,fact=1; int number=5;//It is the number to calculate factorial for(i=1;i<=number;i++) { fact=fact*i; } System.out.println("Factorial of "+number+" is: "+fact); } } import java.io.*; public class Factorial{ public static void main(String args[]) throws IOException { int c,n,fact=1; System.out.print("Enter the number u want to find factorial:"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); n=Integer.parseInt(br.readLine()); for(c=1;c<=n;c++) fact=fact*c; System.out.println("the factorial of "+n+" is "+fact+"\n"); } } public class Factorial { public static void main(String[] args) { int num = 5; long factorial = 1; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } }