0
Sponsored Links


Ad by Google
We have previously listed core java written interview questions. Sometimes interviewer asked you to write a program to find the factorial value of a given number. So In this post, I am simply creating a program to calculate the factorial of given number using a recursion function, about recursion function we separately post a tutorial.

FactorialExample.java
package com.javamakeuse.poc;

public class FactorialExample {

 // recursion method to calculate factorial
 // ex. !5 = 5*4*3*2*1
 public static int findFactorial(int num) {
  if (num < 1) {
   throw new IllegalArgumentException("Not a valid number");
  } else if (num == 1) {
   return 1;
  } else {
   return num * findFactorial(num - 1);
  }
 }
 public static void main(String[] args) {
  System.out.println("Factorial of given number is - " + findFactorial(5));
 }
}

OUT PUT:
Factorial of given number is - 120


Sponsored Links

0 comments:

Post a Comment