Ticker

6/recent/ticker-posts

Header Ads Widget

Java program for factorial

Java program for factorial

Introduction
In this tutorial we gonna learn how to perform factorial or how to Calculate it using a program .
Before going on program let us define what factorial is.


Q)What is factorial?
Sol) Factorial means the product of all the whole numbers from 1 to n; that is, n!.

3! = 3*2*1 =6


So ,this is factorial .let convert it into a useful program .
Before in program  we declare a variable that store user input so that user can enter a number of choice he/she want to find factorial of then what we learnt in definition of factorial we gonna ise that knowledge to produce a logic and after calculating that we gonna give the answer as output.

Lets make it!!!!

Q) Write a java program to calculate a factorial of a number?
Sol)



import java.util.Scanner ;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num,fact=1;
System.out.print( " enter integer :");
num = in.nextInt();
for(int i=num;i>0;i-- )
{
fact*=num;
--num;
}
System.out.printf("the factorial is" + fact+"\n");
}
}



So here we use for loop for ease we can use while loop also,but we use here for loop.

And this program will lead to a simple output as follows.

Output:



<hr size="5" />
<br>
<hr size="5" />
<br>



Some more questions like this you can find out on our website to check more questions for practice 





Post a Comment

0 Comments