Experiment 4
Aim:
To write and execute a Python program using a for loop to print factorial values from 0! to
19! based on the given algorithm.
Theory
The factorial of a number nnn, written as n!n!n!, is defined as:
n!=n×(n−1)×(n−2)×...
Special case:
0!=1
Factorials are widely used in mathematics, probability, combinatorics, and engineering
calculations.
A for loop in Python is used to repeat a block of code a fixed number of times.
Given Algorithm
1. Set f=1
2. Set n=0
3. Repeat the following 20 times:
o Output n,"!=",f
o Add 1 to n
o Multiply f by n
Problem Statement – 1: Printing Factorials from 0! to 19!
# Printing factorial values from 0! to 19!
f = 1 # Step 1: Initialize factorial
n = 0 # Step 2: Initialize number
for i in range(20): # Step 3: Repeat 20 times
print(n, "! =", f)
n=n+1
f=f*n
Class note: A Python program is developed to print the factorial values from 0! to 19! using a
for loop. The factorial of a non-negative integer is the product of all positive integers less
than or equal to that number. A special case is that 0! = 1, which is taken as the starting value
in the program. Since factorial values grow step by step, the program uses an iterative method
rather than computing each factorial separately.
The variable f is first initialized to 1. This variable is used to store the current factorial value.
A for loop is then used with range(20) so that the loop runs exactly 20 times, corresponding
to the values from 0 to 19. In each iteration, the current number n and its factorial value f are
printed. After printing, the factorial value is updated by multiplying it with the next integer,
so that the correct factorial is available in the following iteration.
This method avoids repeated multiplication from the beginning for every number and makes
the program more efficient. For example, once 4! = 24 is known, 5! can be obtained simply
by multiplying 24 × 5. In this way, each factorial is generated from the previous one. The
program therefore demonstrates the practical use of loops, variable updating, and arithmetic
operations in Python.
Viva Voce Questions
1. What is factorial of 0?
2. Why is 0! equal to 1?
3. What is the use of a for loop?
4. What will happen if range(20) is replaced with range(10)?
5. What type of data is stored in variable f?