Search code examples
javaloopsfactorial

How to calculate an factorial with loops in java


I'm trying to write a portion of a program that calculates factorials using loops. I don't have any error messages, but I'm not getting any output.

Are there suggestions for my approach or is there a better approach using loops? Thanks!

import java.util.Scanner;

public class Factorial {
public static void main(String[] args) {

    System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");

    //Create scanner object for reading user input
    Scanner input = new Scanner(System.in);

    //Declare variables
    int number = input.nextInt();
    int factTotal = 1;

    //Execute factorial
    do{
        factTotal = factTotal * number;
        number--;
        while (number >= 1);
    }
    while (number <= 0);{
        System.out.println("That's not a positive integer!");
    }

    System.out.print(factTotal);
}

}


Solution

  • This is the way I would approach the factorial portion of your problem. I would do away with the do/while loops because it appears that you are getting stuck in an infinite loop if you aren't getting output.

    //Call this method when you want to calculate the factorial
    public int factorial(int num){
       for(int i = num-1; i > 1; i--){
           num *= i;
       }
       return num;
    }
    

    This is what it would look like in your code.

    import java.util.Scanner;
    
    public class Factorial {
    public static void main(String[] args) {
    
        System.out.print("Enter a non-negative number that you wish to perform a factorial function on: ");
    
        //Create scanner object for reading user input
        Scanner input = new Scanner(System.in);
    
        //Declare variables
        int number = input.nextInt();
        int factTotal = 1;
    
        if(number > 0){
    
            factTotal = factorial(number);
    
            System.out.print(factTotal);
       }
       else
           System.out.println("This is a negative number");
    }