let us find the factorial of the number using java program. For that, we should learn what is factorial of a number and what is the logic we should put in the program.
Content.
- What is factorial of a number?
- Logic for the program.
- Program.
- Explanation of program.
- Output
- Task.
What is factorial of a number?
Let us have a number n, the product of all the positive numbers until the number is known as factorial of the number.
formula:
n!=n*(n-1)*(n-2)*......*1.
example:
5! = 5*(5-1)*(5-2)*(5-3)*(5-4).
5! = 5*4*3*2*1. (remember until one)
5!=120.
Logic for the program.
There are 3 points to make the program work
- First, assign a value for n.
- Second, subtracted until we have 1.
- Third, multiply the subtracted number.
Program to find the factorial.
class fact
{
public static void main( String args[])
{
int i,n,f=1;
n=Integer.parseInt(args[0]);
for(i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("fact=" +f);
}
}
Explanation of the program.
- We have given the class name has fact.
- public static void main(String arg[]) refers to add a method to the program.
- int i,n,f is declaring the variable and f is initialize with a number 1.(read further to know why?) n is the we give. i is used in formula.
- n=Integer.parseInt(args[0]) is used to convert array of numbers to primitive integer.
- Now, we have to give condition which satisfies all the 3 point above int the logic for the program.
- I choose, for loop to satisfy the condition.
- f*i is the formula.
- System.out.println is used to display the given in output screen(make sure S in System is capital)
know more about for loop here.
Point to be noted:
It is a command line program, that is we will choose the number for which we wanted to find factorial at run time of the program.
example: java fact 3
Output:
compile : javac fact.java
run : java fact 5
fact= 120
known how to execute java program here.
Task to complete:
Try the above program, and find the factorial for other number. note integer is limited memory location.
Comments
Post a Comment