Java Factorial Program


Factorial program 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 (1*2*3*4). The factorial of a negative integer doesn’t exist but the factorial of zero is one. Factorial program in Java using recursion.

Class Factorial{

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.util.*; public class Factorial { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); long n = sc.nextInt(); long sum = 1; for (int i=1; i<=n; i++) { sum *= i; } System.out.println("Factorial of " + n + " is: " + sum); } // end of main method } // end of class Factorial import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number whose factorial is to be found: "); int n = scanner.nextInt(); int result = factorial(n); System.out.println("The factorial of " + n + " is " + result); } private static int factorial(int number) { if (number == 0) { return 1; } else if (number == 1) { return 1; } else { return number * factorial(number - 1); } } } import java.util.Scanner; public class Factorial { public static void main(String args[]){ //We need to take input from the user Scanner scanner = new Scanner(System.in); System.out.print("Enter the number:"); //Stored the entered value in variable int num = scanner.nextInt(); long factorial = 1; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } } 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); } } 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); }} public class Factorial { public static void main(String[] args) { int number = 5; long fact = 1; for(int i = 1; i <= number; i++) { fact = fact * i; } System.out.println("Factorial of "+number+" is: "+fact); } }


Leave a Reply

Your email address will not be published.