Search code examples
javamathcalculatorfactorial

What should I add or remove on my factorial calculator code?


I'm new to coding, so I've been getting confused on what I should add or remove on my code. When I entered the factorial of 2, it also prints out the factorial 1, when I only want the factorial of 2 to print out.

import java.util.Scanner;

public class FactorialCalculator {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        
        int i, fact = 1, number;
                
        System.out.println("<------ Factorial Calculator ------>");
        System.out.print("Enter a positive integer: ");
        number = input.nextInt();
        
        if (number <= 2) {
            for (i = 1; i<=number; i++) {
                fact = fact * i;
                System.out.println("2! = 1 x 2 ");
                System.out.println("The Factorial of 2 is: "+fact);             
            }
        }       
    }
}

output:

<------ Factorial Calculator ------>
Enter a positive integer: 2
The Factorial of 2 is: 1
The Factorial of 2 is: 2

Solution

  • Move your print statement out of the loop.

    if (number <= 2) {
         for (i = 1; i<=number; i++) {
              fact = fact * i;
         }
         System.out.println("The Factorial of 2 is: "+fact);             
    }
    

    But you may want to allow larger values than just 2. And don't forget that both 0! and 1! are equal to 1.

    Try it like this.

    int fact = 1; //starting point for all factorials.
    if (number >= 2) {
        for (int i = 2; i <= number; i++) {
             fact = fact * i;
        }
    }
    System.out.println(number + "! = " + fact);
    

    I think you were confusing <= 2 vs >= 2. <= 2 would only allow values 2, 1, 0, -1, etc to enter the loop. What you wanted was to allow values >= 2 or 2, 3, 4, ...