Pin It

Write a program to find factorial of a number in Java with and without recursion ?

Introduction :-

Hello friends, Today let us begin with a new Java program. Many of serious programmers who are just beginning to code in Java, come across a problem that is, how to write a program that calculate factorial of a number with and without recursion. Learning Java by an example is the most effective technique to inculcate this versatile language. Generally, whatever you know about language its additional when you have power to code small snippets. Learning by coding will not only give you command over the language but also develop the skills in you to code successfully. Java has a good implementation of using the recursion. I will be going to demonstrate the program with and without using concepts of recursion.


Factorial of a number formula :- In general logic to find a factorial of a number is simple and easy. The formula for finding the factorial of a number is : Factorial of a (n) number = n.(n-1).(n-2).(n-3). ...... .32.1 , If suppose we need to find factorial of number 5, it will be 5.4.3.2.1 = 120. In this hub I will be explaining you the code step by step that how a factorial of a number is calculated and printed on the console. The last section would be the code which will demonstrate the working of factorial number calculations. Factorial of a number without recursion :-  On example 1, I will be teaching you how to find factorial of a number without using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Line 1- Java has the ability to reuse the code. There are many predefined classes in Java which we will be using in our factorial calculation program. On line-1 we are importing Scanner class which is been kept in java.util package. Generally to help compiler in locating the class used in the program we use it regularly. Line 3 to 5 - Our Java program begins with a declaration of class named Factorial this class is declared as public so that it can be accessible to all Java class. Class Factorial contains a main method which is the entry point for every Java program. It is a static method so it is called by the JVM without any objects creation on heap. On next line there is a Java statement which just prints the String written in "". The println method just prints whatever is given to it in double quotes. Here in below example it first ask user , "Enter the number of for factorial calculations:". It asks user to enter a number for which he wants to calculate the factorial.
Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
    public static void main (String[ ] args) {
      System.out.println("Enter the number for 
      factorial calculations : "); 

      Scanner scanner = new Scanner(System.in);
      
      int a = scanner.nextInt();
      double fact= 1;

      System.out.println("Factorial of " +a+ ":");
      for (int i= 1; i<=a; i++){
        fact=fact*i;
      }
      System.out.println(fact);
   }
} 
Line 7 to 11 :- On line 7, a new Scanner object is created on heap. The Scanner Class is used to read data from a keyboard or disk. Here variable name is scanner and type is Scanner. Here new operator is used to create a physical Scanner object on the heap. This Scanner object is used to read data from the keyboard. System.in passed into constructor of Scanner object generally reads data from the keyboard in bytes. It is the Scanner object which will convert bytes into types such as ints. Line 10 code uses Scanner method nextInt() to obtain user input as Integer, which he types on the keyboard. Generally upon execution of line, the program waits for user to type an int value from keyboard and press enter. Upon pressing enter value types by user gets assigned to int variable called as a. Factorial of a number with recursion :- On example 2, I will be teaching you how to find factorial of a number using idea of recursion. I will explain the code few lines first , followed by code and then rest of the explanation. The code will give you insight to some basic coding principles used in Java. Let us go for explanation for the code below : A closer look at the program stated below :- Whole code works same as above example. Only difference in the code is one is without recursion and other is with recursion. Line 11 calls static method fact by passing an integer to it. When returning from fact method it calls again fact method with integer value one less than previous integer value. The call sits on the stack till all the methods gets executed when value return from fact is 1. Now fact methods waiting on call gets executed sequentially, till last fact method gets executed and returns the calculated factorial value. Click here to download complete source code 
import java.util.Scanner;

public class Factorial {
  public static void main (String[ ] args) {
    System.out.println("Enter the number for "
         + "factorial calculations : "); 

    Scanner scanner = new Scanner(System.in);
      
    int a = scanner.nextInt();
    int result = fact(a);
    System.out.println("Factorial of " +a+ " is :"+result);
      
  }
  static int fact(int b){
   if(b <= 1)
     return 1;
   else
     return b * fact(b-1);
  }
}
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot