Factorial Calculator Program with Sentinel Value

Answered using GPT-4o mini by AI Answer Generator

Question:

The intent of this program is to allow a user to enter an integer and then print the factorial of that integer. The user must be notified of the sentinel value. The user will continue to be prompted to enter an integer and see the associated factorial until the sentinel value is entered at which point the program will stop. Use a while loop for getting inputs and a for loop to calculate and output the factorial.

  1. The first output should be a program header as described above like: ########## Program #3 – Factorial Calculator ###########
  2. a while loop with a user prompt to enter an integer or sentinel value
  3. a for loop to calculate the factorial of the input
  4. an output • You will need to select a sentinel
Answer:

Here's a Python program that meets your requirements for calculating the factorial of an integer using a while loop for input and a for loop for calculating the factorial. The sentinel value chosen for this program is -1, which will terminate the program when entered by the user.

# Program Header
print("########## Program #3 – Factorial Calculator ###########")

# Sentinel value
sentinel = -1

while True:
    # Prompt user for input
    user_input = input("Please enter a non-negative integer (or -1 to exit): ")
    
    # Convert input to integer
    try:
        number = int(user_input)
    except ValueError:
        print("Invalid input. Please enter an integer.")
        continue

    # Check for sentinel value
    if number == sentinel:
        print("Exiting the program.")
        break
    elif number < 0:
        print("Please enter a non-negative integer.")
        continue

    # Calculate factorial using a for loop
    factorial = 1
    for i in range(1, number + 1):
        factorial *= i

    # Output the result
    print(f"The factorial of {number} is {factorial}.")

Explanation of the Code:

  1. Program Header: The program starts by printing a header to indicate the purpose of the program.
  2. Sentinel Value: The sentinel value is set to -1, which will be used to exit the loop.
  3. While Loop: The program enters an infinite loop where it prompts the user to enter a non-negative integer or the sentinel value.
  4. Input Validation: The program checks if the input can be converted to an integer. If not, it prompts the user again. If the input is negative (but not the sentinel), it also prompts the user again.
  5. For Loop: If a valid non-negative integer is entered, a for loop calculates the factorial of that integer.
  6. Output: The program prints the calculated factorial.

Usage:

  • Run the program, and it will prompt you to enter a non-negative integer.
  • Enter integers to see their factorials.
  • Enter -1 to exit the program.