2 different approaches to find factorial in java | codeYourslf 👨‍💻

In this post, you can learn how to find the factorial of any number using java programming language with 2 different approaches. codeYourslf 👨‍💻

Factorial program in java (2 different ways)

2 different approaches to find factorial in java | codeYourslf 👨‍💻

In this post, you can learn how to find the factorial of any number using java programming language with 2 different approaches.

Approach :-1 "Find factorial using for loop"

package CodeYourslf.allPrograms.factorial;

import java.util.Scanner;

public class byFoorLoop {

    public static void main(String[] args){

      Scanner sc = new Scanner(System.in);

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

      int num = sc.nextInt();

      

      int fact = 1;

      for(int i = 1; i <= num; i++){

        fact = fact * i;

      }

      System.out.println("The factorial is: "+fact);

    }

}

 

Output :- 

2 different approaches to find factorial in java | codeYourslf 👨‍💻

Approach :- 2 "find factorial of a number using while loop"

package CodeYourslf.allPrograms.factorial;

import java.util.Scanner;

public class byWhileLoop {

  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

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

    int num = sc.nextInt();

    int fact = 1;

    // int i = 1;

    while (num > 0) {

      fact = fact * num;

      num--;

    }

    System.out.println("The factorial is: " + fact);

  }

}

 

Code Explanation

Factorial means the product from 1 upto that number. 

         Ex:- factorial of 5 = 1*2*3*4*5

In programming logic we can find that by using loop concept.

Approach :- 1 Explanation

- I have used for loop to solve this problem.

- here I have started the looo from 1 to num. And assigned the code fact = fact * i , here i will be incremented at each iteration. 

And by which each number will multiple one by one to fact and finally the factorial value will store in fact variable.

Approach :-2 Explanation

Here I have used the same concept by in place of for loop I have used while loop to find the factorial of any number in java.

Also read:-

  1. Check Alphabet or not in java :- click
  2. 5 approaches to check Vowel or Consonant :- click

Hey if you learn something new from this post, please share with your friends.

👉 If you have any doubt or any query regarding this topic or anything or, don't feel bad to write it on the comment.

`

تعليقان (2)

  1. Please give your feedback
  2. good work
Hey Please 👏, feel free to share your opinion 🌍
© codeYourslf. All rights reserved. Distributed by Pixabin