Home CPSC 110

Factorials

Objective

To gain experience working with loops.


Task

For this assignment, you will write a program that calculates the factorial of a number. The factorial of a number $x$, written as $x!$ is equal to the product of all positive numbers preceding $x$:

$x! = x \cdot (x - 1) \cdot (x - 2) ... \cdot 3 \cdot 2 \cdot 1$

The factorial of 0 is defined to be equal to 1.


Details

  1. Start by asking the user for a number. You should keep asking them for a number until they put in one that is 0 or greater, using a while loop.
  2. Create a variable to store the factorial's value. You should set this equal to 1 initially.
  3. You should then use a for loop to perform the factorial computation. It should loop for each number from 1 through the user's input.
  4. Inside the loop, you'll need to multiply the loop's value into your variable storing the factorial value.
  5. After the loop is done, print the value of the factorial.

Testing

Below is a table of factorial values so you can test your program:

$x$$x!$
01
11
22
36
424
5120
6720
75040
840320

Submitting

When your program is finished, email the .py file to ifinlay@umw.edu. Please attach it as a file instead of copying it into the body of the message!

Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.