Factorial of a number in C

The factorial of a number is a fundamental concept in mathematics, frequently used in permutations, combinations, and various mathematical computations. In programming, computing the factorial is a common exercise to illustrate loops and recursion. This article will guide you through three different ways to write a program to find the factorial of a number in C: using a loop, using recursion, and using an array.

Write a program to find the “Factorial of a number in C”

Method 1) Program to find the “Factorial of a number in C using a Loop”

Using loops to calculate the factorial is straightforward and efficient. The process involves initializing a variable to hold the result and iteratively multiplying it by each integer up to the target number.

Code Example

#include <stdio.h>

int main() {
    int n, i;
    unsigned long long factorial = 1;

    printf("Enter an integer: ");
    scanf("%d", &n);

    // Check if the number is negative
    if (n < 0)
        printf("Factorial of a negative number doesn't exist.\n");
    else {
        for (i = 1; i <= n; ++i) {
            factorial *= i;
        }
        printf("Factorial of %d = %llu\n", n, factorial);
    }

    return 0;
}

Explanation of the Code

  • Input and Initialization: The program starts by reading an integer from the user. It then initializes a variable, factorial, to 1.
  • Validation: It checks if the input number is negative. If it is, it prints an error message because factorials for negative numbers are undefined.
  • Loop: If the number is non-negative, a for loop multiplies the factorial variable by each number from 1 to the input number.
  • Output: The result is displayed to the user.

Method 2) Program to find the “Factorial of a number in C using Recursion”

Recursion is a powerful technique where a function calls itself to solve a smaller instance of the same problem. For factorials, this involves calling the factorial function within itself.

Code Example

#include <stdio.h>

unsigned long long factorial(int n);

int main() {
    int n;

    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n < 0)
        printf("Factorial of a negative number doesn't exist.\n");
    else
        printf("Factorial of %d = %llu\n", n, factorial(n));

    return 0;
}

unsigned long long factorial(int n) {
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}

Explanation of the Code

  • Function Declaration: Declare the factorial function at the beginning. It returns an unsigned long long type because factorials can grow very large.
  • Base Case: Inside the factorial function, check the base case first. If n is 0, the function returns 1. If n is 0, the function returns 1.
  • Recursive Case: For any other value of n, the function returns n multiplied by the factorial of n-1.
  • Main Function: The main function handles input and calls the recursive factorial function, displaying the result.

Method 3) Program to find the “Factorial of a number in C using an Array”

For educational purposes, you can use an array to store intermediate results of the factorial computation. Although you don’t commonly use this method due to its complexity and memory usage, it demonstrates how arrays work in computation.

Code Example

#include <stdio.h>

int main() {
    int n, i;
    printf("Enter an integer: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Factorial of a negative number doesn't exist.\n");
    } else {
        unsigned long long factArray[n + 1];
        factArray[0] = 1;

        for (i = 1; i <= n; i++) {
            factArray[i] = i * factArray[i - 1];
        }

        printf("Factorial of %d = %llu\n", n, factArray[n]);
    }

    return 0;
}

Explanation of the Code

  • Array Initialization: An array factArray is declared to hold the factorial values up to n. The array is initialized with factArray[0] = 1.
  • Loop: A for loop iterates from 1 to n, filling the array with the factorial values. Each element is calculated as i * factArray[i - 1].
  • Output: Display the factorial of the number by accessing the last element of the array.

These three methods—using a loop, recursion, and an array—demonstrate different ways to solve the same problem in C. Using a loop is the most straightforward and efficient for small numbers, while recursion provides a clear and concise approach. Using an array, though less practical, showcases another way to handle intermediate computations. By understanding these methods, you can choose the one that best suits your needs and constraints in different scenarios.

Categories C

Leave a Comment