Back to Lab HomeLab Exercise – 03

Experiment 3 – Factorial Calculation

Aim

To calculate the factorial of a given number using iterative approach (loops) in C programming. Factorial of n (n!) is the product of all positive integers from 1 to n. This experiment helps students understand loop constructs, iterative problem-solving, and handling edge cases in programming.

Through this experiment, students will learn to implement iterative solutions, understand the difference between iterative and recursive approaches, and practice using for and while loops effectively.

Learning Outcomes

After completing this experiment, students will be able to:

  • Understand the concept of factorial and its mathematical definition
  • Implement iterative solutions using for and while loops
  • Handle edge cases (0!, negative numbers) in programs
  • Choose appropriate data types for large factorial values
  • Write clean, efficient code for mathematical calculations
  • Compare iterative vs recursive approaches to problem-solving
  • Debug and test programs with various input values
  • Apply loop constructs to solve real-world mathematical problems

Algorithm

The algorithm to calculate factorial iteratively involves multiplying numbers from 1 to n sequentially:

Algorithm Steps:

  1. Start: Begin the program execution
  2. Input: Read a positive integer n from the user
  3. Validate: Check if n is negative
    • If negative, display error message and exit
    • If non-negative, proceed to calculation
  4. Initialize: Set factorial = 1 and i = 1
  5. Check Base Case: If n == 0 or n == 1
    • Set factorial = 1 (by definition, 0! = 1 and 1! = 1)
    • Skip to output step
  6. Iterate: For i from 1 to n
    • Multiply factorial by i
    • Increment i by 1
    • Repeat until i > n
  7. Output: Display the factorial result
  8. Stop: End the program

Mathematical Formula: n! = n × (n-1) × (n-2) × ... × 2 × 1, where 0! = 1 by definition.

Procedure

  1. Include stdio.h header file
  2. Declare variables: n (input number) and factorial (result, initialize to 1)
  3. Read the number from user
  4. Check if number is negative (factorial undefined for negative numbers)
  5. Use a loop (for or while) to multiply numbers from 1 to n:
    • Initialize counter i = 1
    • While i <= n, multiply factorial by i
    • Increment i
  6. Display the factorial result
  7. Handle edge case: factorial of 0 is 1

Flowchart

START
  │
  ├─→ Declare variables: n, factorial = 1, i
  │
  ├─→ Read n
  │
  ├─→ IF (n < 0)
  │   │
  │   └─→ Display "Factorial not defined for negative numbers"
  │   └─→ END
  │
  ├─→ IF (n == 0 || n == 1)
  │   │
  │   └─→ factorial = 1
  │
  ├─→ ELSE
  │   │
  │   ├─→ FOR i = 1 to n
  │   │   │
  │   │   └─→ factorial = factorial * i
  │   │
  │   └─→ END FOR
  │
  ├─→ Display "Factorial of " + n + " = " + factorial
  │
  └─→ END

Program Code

#include <stdio.h>

int main() {
    int n, i;
    long long factorial = 1;  // Use long long for large numbers
    
    // Input number
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    
    // Check for negative number
    if (n < 0) {
        printf("Error! Factorial is not defined for negative numbers.\n");
        return 1;
    }
    
    // Calculate factorial
    if (n == 0 || n == 1) {
        factorial = 1;
    } else {
        for (i = 1; i <= n; i++) {
            factorial *= i;
        }
    }
    
    // Display result
    printf("Factorial of %d = %lld\n", n, factorial);
    
    return 0;
}

// Alternative using while loop:
/*
i = 1;
while (i <= n) {
    factorial *= i;
    i++;
}
*/

Sample Input and Output

Sample 1:

Input:

Enter a positive integer: 5

Output:

Factorial of 5 = 120

(5! = 5 × 4 × 3 × 2 × 1 = 120)

Sample 2:

Input:

Enter a positive integer: 0

Output:

Factorial of 0 = 1

Sample 3:

Input:

Enter a positive integer: 7

Output:

Factorial of 7 = 5040

Sample 4:

Input:

Enter a positive integer: -5

Output:

Error! Factorial is not defined for negative numbers.

Use Case / Real-world Relevance

Factorial calculation is fundamental in mathematics and computer science:

  • Combinatorics: Calculating permutations and combinations (nPr, nCr)
  • Probability Theory: Computing probabilities in various scenarios
  • Statistics: Used in binomial distribution and other statistical formulas
  • Algorithm Analysis: Understanding time complexity of algorithms (e.g., generating all permutations)
  • Taylor Series: Used in mathematical series expansions (e.g., e^x, sin(x))
  • Cryptography: Some encryption algorithms use factorial-based calculations
  • Game Development: Calculating possible moves or combinations in puzzle games
  • Data Structures: Used in tree structures and graph algorithms

Understanding loops and iterative problem-solving is crucial for efficient programming. This experiment teaches you how to break down a mathematical problem into iterative steps. Factorial calculation is a fundamental operation that appears in many algorithms and mathematical computations, making it an essential skill for any programmer.

Viva Questions

Q1: What is factorial? Give the mathematical definition.

Factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. Mathematically: n! = n × (n-1) × (n-2) × ... × 2 × 1, with special case 0! = 1.

Q2: Why is 0! equal to 1?

0! = 1 by definition. This is consistent with the empty product convention in mathematics and makes formulas like the binomial coefficient work correctly. It's also consistent with the gamma function, which extends factorial to real numbers.

Q3: What data type should be used for storing factorial? Why?

Use long long or unsigned long long because factorial values grow very rapidly. For example, 20! = 2,432,902,008,176,640,000, which exceeds the range of int. For very large factorials, consider using libraries that handle arbitrary precision arithmetic.

Q4: What is the difference between iterative and recursive approaches for factorial?

Iterative approach uses loops and is more memory-efficient (O(1) space) and usually faster. Recursive approach calls the function itself and uses the call stack (O(n) space), which can cause stack overflow for large n. Iterative is preferred for factorial calculation.

Q5: What happens if we calculate factorial of a negative number?

Factorial is not defined for negative numbers in standard mathematics. The program should check for negative input and display an error message. Attempting to calculate factorial of negative numbers leads to undefined behavior or infinite loops.

Q6: Can we use a while loop instead of for loop? Show how.

Yes, while loop can be used: int i = 1; while (i <= n) { factorial *= i; i++; }. Both for and while loops are equivalent for this problem. Choose based on readability and coding style preferences.

Q7: What is the time complexity of the iterative factorial algorithm?

The time complexity is O(n) because the loop executes n times, performing constant-time multiplication in each iteration. The space complexity is O(1) as we only use a fixed amount of extra memory regardless of input size.

Q8: Why do we initialize factorial to 1 and not 0?

We initialize to 1 because multiplication by 1 is the identity operation. If we initialize to 0, all multiplications would result in 0 (since anything × 0 = 0), giving incorrect results. Starting with 1 ensures correct multiplication accumulation.

Q9: What is the largest factorial that can be calculated using long long?

long long can store values up to 9,223,372,036,854,775,807. Factorial of 20 (20! = 2,432,902,008,176,640,000) fits, but 21! exceeds this range, causing overflow. For larger factorials, use arbitrary precision libraries or handle overflow detection.

Q10: How would you modify the program to calculate factorial using recursion?

Create a recursive function: long long factorial(int n) { if (n <= 1) return 1; return n * factorial(n-1); }. The base case is n ≤ 1 returning 1, and the recursive case multiplies n by factorial(n-1). This is less efficient than iteration but demonstrates recursion concepts.

Related Links

🔹 Author: Dr. J. Siva Ramakrishna

🔹 Institution: Narayana Engineering College, Gudur

🔹 Last Updated: 9 January 2026