﻿ Java program to find factorial of a given number - Programming Posts

# Java program to find factorial of a given number

go to site The Factorial of a non-negative number n is the product of all positive integers less than or equal to n and is represented by n!.

http://web-impressions.net/fister/3563 n! = 1 * 2 * 3 * 4 * 5 * ………………………..  * (n-1) * n.

watch for example

follow url 5! can be calculated as 1 * 2 * 3 * 4 * 5 =120.

sites de rencontre gratuit au senegal The value of 0! is 1 according to Empty convention.

### Algorithm:

click Step 1: START.

strategie professionali opzioni binarie Step 2: Read Number n.

rencontre gratuite 38 Step 3: Initialize two variables, say i = 1 and fact = 1.

http://curemito.org/estorke/4306 Step 4: fact = fact * i.

https://www.gemeinde-stammham.de/destolo/3350 Step 5: i = i+1.

Step 6: Repeat step 4 and 5 until i=n.

alavert 10 mg dose Step 7:  Print fact.

amitriptyline 10mg hangover Step 8: STOP.

### Explanation:

Let the number whose  factorial is to be found be stored in num.

A new variable “fact” is declared as int data type and is intialized to 1 i.e., fact =1.

Now, we need to multiply the variable “fact” with all the natural numbers 1 to num.

For this purpose, we use a for loop with a counter i that ranges from 1 to num. Within the loop, the existing value of fact will be multiplied with the loop counter.

for (int i = 1; i <= num; i++) {
fact = fact * i;
}
To understand how the above loop works ,Let us take a small number num = 3 . Before entering the loop, fact would be initialized to one.

The loop will execute thrice with the value of i = 1, 2 and 3. When the value of i becomes 4, the loop condition fails. When the value of i is 1, the existing fact would be multiplied with 1 which again gives one. In the second iteration, fact will be multiplied with 2 and in the third iteration with 3. These calculations are shown below:

fact = 1
i = 1           fact = fact * i = 1 * 1 = 1
i = 2           fact = fact * i = 1 * 2 = 2
i = 3           fact = fact * i = 2 * 3 = 6

if we enter the number as 0, it doesn’t get  into the loop for iteration and it directly prints the fact value which is initialized to 1.

### Output:

C:\Users\santo\Desktop\new>javac Factorial.java

C:\Users\santo\Desktop\new>java Factorial

*** www.programmingposts.com ***

>>> JAVA Program to find Factorial of a given number <<<

Enter a number:
6
The factorial of 6 is 720.