-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Sunday, October 25, 2020

Java Program To Find The Factorial Of A Number Using Recursion Entered By The User

  • October 25, 2020
  • by

 

Java Program To Find The Factorial Of A Number Using Recursion Entered By The User

In this Java Program, we calculate the factorial of the number using recursion entered by the user.

Factorial of n is the product of all the positive descending integers. It is denoted by n!

For example : 4! = 4 * 3 * 2 * 1 = 24

Logic : fact = fact * i;

Step 1 : Import Scanner Class

Step 2 : Create main method

Step 3 : Create scanner object for capturing the user input

Step 4 : Ask the user to enter the number

Step 5 : Store the entered value in the variable num

Step 6 : Call the user defined function fact

Step 7 : Print the number

Step 8 : Create a static function which returns 1

Step 9 : Create recursion function which calls itself

Program :

import java.util.Scanner;

public class FactorialDemo {

    public static void main(String[] args)

    {

        //Scanner object for capturing the user input

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the number:");

        //Store the entered value in variable

        int num =sc.nextInt();

        //Call the user defined function fact

        int factorial = fact(num);

        System.out.println("Factorial of entered number is:"+factorial);

    }

    static int fact(int n)

    {

        int output;

        if(n==1){

            return 1;

        }

                //Recursion: Function calling itself

        output = fact(n-1)*n;

        return output;

    }    

}

Output :

Enter the number:

5

Factorial of entered number is:120

For execution of the same do visit my YouTube Channel :

https://youtu.be/IBSxhMDbMrw


A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages