Ads

How to calculate factorial of a given number?

Ads

View Answers

May 23, 2012 at 6:00 PM

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Factorial { public static void main(String args[]) throws IOException { System.out.println("Please Input Any Number"); int num = 0; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String data = (String) br.readLine(); num = Integer.parseInt(data); int result = num; for (int i = 1; i < num; i++) { result = result*i; } System.out.println(result); } }

**Description:** - Factorial of any number n is represented by !n and is equal to
n*(n-1)*(n-2)*(n-3)?.*1.
BufferReader () is used for user input.BufferReader consider inputted value as String so for int value you have to use Integer.parseInt().
For loop from 1 to num-1 calculating the factorial value of num as result=result*i. Initial value of result is num.

May 25, 2012 at 12:23 AM

Explanation : Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to java programming, recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.

The classic example of recursion is the computation of the factorial of a number. The factorial of a number N is the product of all the whole numbers between 1 and N. for example, 3 factorial is 1Ã?2Ã?3, or 6. Here is how a factorial can be computed by use of a recursive method

Ads

Related Tutorials/Questions & Answers:

Ads

- Java Tutorials
- Java Code example
- Java Programming
- Java Beginners Examples
- Applet Tutorials
- Awt Tutorials
- Java Certification
- Interview Question
- Java Servlets Tutorial
- Jsp Tutorials
- Java Swing Tutorials
- JDBC Tutorial
- EJB Tutorials
- Java Server Faces (JSF) Tutorial
- WAP Tutorial
- Struts Tutorial
- JAXB Tutorial
- Spring FrameWork Tutorial
- SOA&Web Services Tutorials
- Bioinformatics Tutorials
- MySQL Tutorials
- JAVA DOM Tutorial
- XML Tutorial
- EAI Articles
- Many Programming Tutorials Links
- Tutorials Books
**Java Script Tutorial****Ajax Tutorial****Dojo Tutorials****Programming Books****Trainings****Flex****Ant****RDF**

Ads