Write a Java Program to find Factorial of given number using Recursive and Non-Recursive approach ? | StudyEcart | CODE009

Factorials: A Quick Recap:

Before we dive into the code, let's refresh our memory about factorials. A factorial of a non-negative integer 'n' is the product of all positive integers less than or equal to 'n'. It's denoted as 'n!' and can be calculated as:  

n! = n * (n - 1) * (n - 2) * ... * 2 * 1  


Recursive Approach: Calculating Factorials:

Recursive programming involves breaking down a problem into smaller sub-problems of the same type. Let's see how we can calculate factorials using the recursive approach, with user input:

 
import java.util.Scanner;

public class RecursiveFactorial {
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        
        int result = factorial(num);
        System.out.println("Factorial of " + num + " is: " + result);
        
        scanner.close();
    }
}


(code-box)



Non-Recursive Approach: Calculating Factorials

Non-recursive programming involves iterative techniques to solve problems without function calls. Here's how you can calculate factorials non-recursively, with user input:

 
import java.util.Scanner;

public class NonRecursiveFactorial {
    public static int factorial(int n) {
        int result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        
        int result = factorial(num);
        System.out.println("Factorial of " + num + " is: " + result);
        
        scanner.close();
    }
}


(code-box)


Conclusion:

You've now embarked on a journey to calculate factorials using both recursive and non-recursive approaches in Java. By incorporating the `Scanner` utility, you've added a user-friendly touch to the programs. Understanding strong numbers provides us with an extra layer of mathematical intrigue that we can use in practical programming scenarios. So keep coding, exploring, and expanding your programming toolkit!

🚀 Elevate Your Career with Studyecart! 📚📊

🔥 Get instant job notifications and ace interviews with Studyecart. 📌

(getButton) #text=(Download Now) #icon=(download) #color=(#1bc517)

#StudyecartApp #CareerBoost

Post a Comment

0 Comments