Java Programming : Factorial of a number

Example

Input
5 
Output
120

Required to Know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out. print(), and use of for loop, and Use of Data types

Steps

  • Take range as input from the user.

  • Initialize a variable as 1 which will later perform the function of the factorial.

  • Run the for loop till the given range. Inside the for loop use the variable which is being initialized as 1.

  • Factorial needs to get updated in each iteration.

  • Now print the factorial.

Program

import java.util.Scanner; 
public class Mavenproject1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int i, n;
        int fact = 1; 
        n = sc.nextInt();
        for(i=1;i<=n;i++){
            fact = fact * i; 
        }
        System.out.print(+fact);
    }
}