Skip to study material
← Question index

QUESTION 34 · Loop Applications

Write a C program to calculate factorial using a loop.

5 marks

Answer in brief

For a non-negative integer n, n! is the product of integers from 1 through n. By definition, 0! equals 1.

Algorithm

  1. Read n and accept values from 0 through 20.
  2. Set factorial to 1.
  3. Multiply factorial by each integer i from 2 through n.
  4. Print factorial.

Worked trace

For n = 5, factorial starts at 1. Multiplication by 2 gives 2; by 3 gives 6; by 4 gives 24; and by 5 gives 120. When i becomes 6, the test fails and the program prints 120.

Boundary cases

For n = 0 or n = 1, the loop body is skipped and the result remains 1. Negative integers are rejected because this program uses the elementary factorial definition. The program does not attempt a factorial above 20, because factorial grows rapidly and a fixed-width integer cannot store arbitrary results.

Data type choice

unsigned long long can represent at least the range needed for 20!. The format %llu matches that type. Choosing a wider type does not remove every limit; it only increases the supported range. An input must still be representable by the type used to read it.

Time and space complexity

For n >= 2, the loop performs n - 1 multiplications. The number grows linearly with n, giving O(n) time for this algorithm under fixed-width arithmetic. The input bound is a safety limit on the example. The program stores a fixed number of values, so auxiliary space is O(1).

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("Factorial = %llu\n", factorial);
    return 0;
}

Sample input and output

Input

5

Output

Factorial = 120

Related exam questions

Related questions in the loops category from the supplied papers. The marks below are the printed allocations, including any combined subquestion.

  • September/October 2021 · Q6(b) · 8 marks

    How is an entry-controlled loop different from an exit-controlled loop? Explain.

    Paper P01 · page 1
  • March/April 2023 · Q2(b) · 5 marks

    Devise an algorithm for the sum of n numbers using while and for loops.

    Paper P02 · page 1

View this category in the exam question bank →