CC-5 : Find factorial of number.
Description:
Given an input number, find its factorial.
Test cases and expected outputs:
| Input Parameters |
Expected outputs |
| Number: 6
|
Factorial: 720
|
| Number: 7
|
Factorial: 5040
|
Pseudocode:
DecimalToBinary(num):
| The number to be checked is received as input parameter.
|
| If num==0, return 1; (base case).
|
| Recursively call factorialOfNum() with parameter num-1 and multiply return value fromrecursive call with num and return the calculated value..
|
Code:
public int factorialOfNumber(int num){
if (num == 0) {
return 1;
}
return num * factorialOfNumber(num-1);
}
Click here to download and run code and test cases !
Below fully running code can be copied and run on Eclipse or other Java IDEs. Refer the classname in code below. If the class name below is "A", save the code below to a file named A.java before running it.
Be sure to try your own test cases to enhance your understanding !
You can also tweak the code to optimize or add enhancements and custom features.
public class RecursionFactorialOfNumber {
public int factorialOfNumber(int num){
if (num == 0) {
return 1;
}
return num * factorialOfNumber(num-1);
}
public static void main(String[] args) {
/***********************
Test cases given below:
**********************/
int retVal;
try {
RecursionFactorialOfNumber rcn=new RecursionFactorialOfNumber();
int num=10;
retVal=rcn.factorialOfNumber(num);
System.out.println("Number: "+num);
System.out.println("Factorial: "+retVal);
System.out.println();
num=6;
retVal=rcn.factorialOfNumber(num);
System.out.println("Number: "+num);
System.out.println("Factorial: "+retVal);
System.out.println();
num=7;
retVal=rcn.factorialOfNumber(num);
System.out.println("Number: "+num);
System.out.println("Factorial: "+retVal);
}catch (Exception exception) {
System.out.print("Exception: "+ exception);
exception.printStackTrace();
}
}
}