Question

Hi I need to print process of factorial calculation. E.g. If the user's input is 5, the system should print out "5 * 4 * 3 * 2 * 1 = 120"

I have this code:

 public static void factorial()
{
    Scanner sc = new Scanner(System.in);
    int factorial = 1;
    int count;

    System.out.println(me+", This is option 2: Calculate a factorial");
    System.out.print("Enter your number: ");
    int number = sc.nextInt();
    System.out.println();

    if (number>0)
        {
            for (count=1; count<=number; count++)

            factorial = factorial*count;

            System.out.println(" = "+factorial);
            System.out.println();
        }
    else
    {
        System.out.println("Enter a positive whole number greater than 0");
        System.out.println();
    } 

}    

I have tried insert this code:

 System.out.print(count+" * ");

But the output is "1 * 2 * 3 * 4 * 5 * = 6". So the result is wrong too. How can I change the code? Thanks

Was it helpful?

Solution

The problem is that you didn't put braces {} on your for statement:

if (number>0)
{
    for (count=1; count<=number; count++)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count < number)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}

Also, if you're concerned about the order (1,2,4,5 instead of 5,4,3,2,1) you could do the following (changing the for loop):

if (number>0)
{
    for (count=number; count>1; count--)
    {
        factorial = factorial*count;
        System.out.print(count);
        if(count > 2)
            System.out.print(" * ");
    }

    System.out.println("Factorial of your number is "+factorial);
    System.out.println();
}

OTHER TIPS

Use this code. It checks whether you are in the last iteration and adds " * " otherwise

System.out.print(count + ((count < number) ? " * " : ""));

Otherwise you could also use:

for (count=1; count < number; count++) { // Note: < instead of <=
    factorial *= count;
    System.out.print(count + " * ");
}
factorial *= number;
System.out.println(number + " = " + factorial);

Something like this should accomplish what you're looking for:

        int number = 5;
        int factorial = 1;
        String factString = "";
        for (int count = number; count > 0; count--) {
            factorial = factorial * count;
            if (count == number) {
                factString += count;
            } else {
                factString += " * " + count;
            }
        }

        System.out.println("Factorial of " + factString + " is " + factorial);
        System.out.println();

The code will count down from the number entered. This will print all in one line by storing your progress in a string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top