Search code examples
javafactorial

I am having difficulties writing a factorial program


the program should ask user for a positive integer and print a factorial table. And if the input is less than 0 the output or program should stop.

Give me a positive integer: 5

Output:

5! = 5 x 4 x 3 x 2 x 1

The factorial of 5 is 120

Give me a postive integer: -5

Output: invalid Input! Programmed Stop

P.s: i am a beginner. I am using Netbean IDE


Solution

  • This should work. Just loop through the numbers.

    var input = prompt("What number would you like me to give you the factorial of?");
    if (input > 0) {
      var answer = 1;
      var string = input + " =";
      for (var i = input; i >= 1; i--) {
        answer *= i;
        string += " " + i
        if (i != 1) {
          string += " x"
        }
      }
    
      console.log(string)
      console.log("The factorial of " + input + " is " + answer)
    } else {console.log("Invalid input! Program stopped.")}

    Java (assumes the input is in the variable input):

    if (input > 0) {
      int answer = 1;
      String stringAnswer = input + " =";
      for (int i = input; i >= 1; i--) {
        answer *= i;
        stringAnswer += " " + i
        if (i != 1) {
          stringAnswer += " x"
        }
      }
    
      System.out.println(stringAnswer)
      System.out.println("The factorial of " + input + " is " + answer)
    } else {System.out.println("Invalid input! Program stopped.")}