Notice: Constant WP_MEMORY_LIMIT already defined in /home/javawith/public_html/codesjava.com/wp-config.php on line 107

Notice: Constant WP_MAX_MEMORY_LIMIT already defined in /home/javawith/public_html/codesjava.com/wp-config.php on line 108
Factorial program recursion in java - CodesJava

CodesJava

Easy learning with example program codes

Factorial Program Using Recursion in Java


Notice: Undefined variable: footnotelist in /home/javawith/public_html/codesjava.com/wp-content/plugins/latex2html/inc/core.php on line 475

 

Program to find factorial of given number by recursion.

/**
 * This program is used to find factorial of given number by recursion.
 * @author CodesJava
 */
public class FactorialByRecursion {
      /**
       * This method is used to find factorial of given no. by recursion.
       * @param num
       * @return int
       */
      static int fact(int num){
            //Factorial of 0 is 1.
            if (num == 0)
                  return 1;
            else
                  return num * fact(num-1);
      }     
 
      public static void main(String args[]){
            int num = 5, factorial;
            //method call
            if(num > 0){
               factorial = fact(num);
               System.out.println("Factorial of "+num+" is "+ factorial);
            }else{
                  System.out.println("Number should be non negative.");
            }          
      }
}

Output:

Factorial of 5 is 120

 

Please follow and like us:
error
Posted in Java   

Core Java Tutorial








Copyright © 2019 CodesJava DMCA.com Protection Status