Skip to study material
← Question index

QUESTION 22 · Worked algorithms

Develop an algorithm and flowchart to calculate the factorial of a non-negative integer.

5 marks

Answer in brief

The factorial of a non-negative integer n is the product of the integers from 1 to n. It is written as n!. By definition, 0! = 1.

Algorithm

  1. Read n: Use an integer in the supported range.
  2. Initialise the product: Set factorial = 1 and i = 2.
  3. Multiply: While i <= n, set factorial = factorial × i.
  4. Move to the next factor: Increase i by 1 and repeat the test.
  5. Display factorial: It contains the required product.

Example: 5!

For n = 5, the product starts at 1. Multiplying by 2 gives 2; multiplying by 3 gives 6; multiplying by 4 gives 24; multiplying by 5 gives 120. Thus 5! = 120. Each loop step adds one required factor to the product.

Initial value and boundary cases

The product must start at 1, not 0. A product that starts at zero stays zero after every multiplication. When n is 0 or 1, the loop is not entered and the answer remains 1. Negative inputs are rejected because they are outside this elementary factorial definition.

Range of the program

Factorials grow quickly. The example accepts only 0 through 20 and uses unsigned long long. This type has enough guaranteed range for 20!, but not for every factorial. A larger input needs an overflow check or a different way to store large numbers.

Time and space complexity

The repeated multiplication takes O(n) time in the usual analysis, because the number of loop steps grows with n. Only a few variables are used, so extra space is O(1). The supplied fixed-width program restricts the input to avoid overflow.

Diagram or flowchart

For n from 0 to 20, initialise result to 1 and i to 2; multiply while i is at most n, otherwise print the result. Unsupported n is rejected.
Factorial with a loop · Download diagram

C program and output

/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
    int n;
    unsigned long long factorial = 1;
    if (scanf("%d", &n) != 1 || n < 0 || n > 20) {
        puts("Unsupported input");
        return 1;
    }
    for (int i = 2; i <= n; ++i) {
        factorial *= (unsigned long long)i;
    }
    printf("%d! = %llu\n", n, factorial);
    return 0;
}

Sample input and output

Input

5

Output

5! = 120

Key points

  • 0! is 1.
  • Check the numeric range before multiplying.