Factorial Program in JAVA - Step by Step
--------------------------------------------------------------------------------
In any Programming Language, to solve a given problem, must divide that problem and then solve that problem.
In this Factorial program, we divide our problem into the three parts.
1) Imagine Output Screen with common Messages
2) Make a Logic on a Paper with pen or pencil
3) Implement that Logic (Step 2) in code
Imagine Output Screen with common Messages
Make a Logic on a Paper with pen or pencil
Factorial.java
-------------------------------------------------------------------------------
import java.util.Scanner;
class factorial
{
public static void main(String args[])
{
int fact = 1;
System.out.print("Enter a Number:-");
//Create Object of scanner calss
Scanner scn = new Scanner(System.in);
int userValue = scn.nextInt();
for(int i=1;i<=userValue;i++)
{
fact = fact * i;
//i==1 --> 1 = 1 * 1 fact=1
//i==2 --> 2 = 1 * 2 fact=2
//i==3 --> 6 = 2 * 3 fact=6
//i==4 --> 24 = 6 * 4 fact=24
//i==5 --> 120 = 24 * 5 fact=120
}
System.out.println("Factorial of "userValue+" is "+fact);
}
}
Output
Comments
Post a Comment