In this article we will see how to find factorial of a number in Java ?

There are two ways to find factorial of given positive number in Java. 1) Using For Loop 2) Using Recursion So we will cover both ways - 1) factorial program in java using recursion. 2) factorial program in java using for loop.

Lets say we want to find factorial of number 4. This is annotated as 4! = 4 * 3 * 2 * 1 = 24. Lets see both the ways using Java.

public class Factorial { public static void main(String[] args) { int number = 5; int factorial = 1; // 1. using for loop for (int i = 1 ; i <= number ; i++) { factorial = factorial * i; } System.out.println("Factorial using for loop = " + factorial); System.out.println("Factorial using recursion = " + factorial(number)); } // 2. using recursion public static int factorial(int number) { if (number == 1) { return 1; } return number * factorial(number-1); } }

## 2 Comments

Hello I'm registered student of your jasper course in Udemy. What topics in Java should I need to know for Jasper expertise

ReplyDeleteYou need to have knowledge of core Java. If you want to get further from the course then you can go for Spring Boot as well.

Delete