Factorial of a number in java without recursion | Iterative approach | while loop

In this tutorial, we will find factorial of a entered number iteratively.

Steps:

  • Firstly, we will create a noRecursion method having parameter n.
  • Initialize fact = 1.
  • Start a while loop until, n>0
  • While loop will be executed until step 3 condition is true.
  • When n == 0 , while loop turns false, return fact.
  • Then, we will store returned value from noRecursion method into result datatype. (as show in main() method).
  • At last, print the result.


Code Approach:(JAVA)

package Recursion;

import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int result = noRecursion(n);
System.out.println("Factorial of "+n+": " + result);
}

public static int noRecursion(int n) {
int fact = 1;
while (n > 0) {
fact *= n;
n--;
}
return fact; // this will return the ans;
}
}

Output:


Enter a number: 7
Factorial of 7: 5040
Previous Post Next Post

Contact Form