Compute Factorials in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to compute factorials in C programming. The lab covers two methods for calculating the factorial of a number: using an iterative loop and a recursive function. You will start by reading an integer input from the user, then implement both the loop-based and recursive approaches to compute the factorial, and finally print the result.

The lab provides step-by-step instructions and code examples to guide you through the process, ensuring a comprehensive understanding of factorial computation in C.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/recursion("`Recursion`") subgraph Lab Skills c/output -.-> lab-435147{{"`Compute Factorials in C`"}} c/variables -.-> lab-435147{{"`Compute Factorials in C`"}} c/for_loop -.-> lab-435147{{"`Compute Factorials in C`"}} c/user_input -.-> lab-435147{{"`Compute Factorials in C`"}} c/function_declaration -.-> lab-435147{{"`Compute Factorials in C`"}} c/recursion -.-> lab-435147{{"`Compute Factorials in C`"}} end

Read an Integer n

In this step, you will learn how to read an integer input for calculating its factorial in a C program. We'll focus on creating a simple program that prompts the user to enter a number and stores it for further computation.

First, let's create a new C file in the project directory:

cd ~/project
nano factorial.c

Now, add the following code to read an integer input:

#include <stdio.h>

int main() {
    int n;

    printf("Enter a number to calculate its factorial: ");
    scanf("%d", &n);

    printf("You entered: %d\n", n);

    return 0;
}

Let's compile and run the program:

gcc factorial.c -o factorial
./factorial

Example output:

Enter a number to calculate its factorial: 5
You entered: 5

In this code:

  • printf() is used to display a prompt to the user
  • scanf() reads the integer input from the user
  • %d is the format specifier for integers
  • &n passes the memory address of the n variable to store the input

Compute n! Using a Loop or Recursion

In this step, you will learn two methods to compute the factorial of a number: using an iterative loop and a recursive function. We'll modify the previous factorial.c file to implement both approaches.

Let's update the factorial.c file:

cd ~/project
nano factorial.c

Add the following code to implement factorial calculation using a loop and recursion:

#include <stdio.h>

// Factorial calculation using iterative loop
unsigned long long factorialLoop(int n) {
    unsigned long long result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

// Factorial calculation using recursion
unsigned long long factorialRecursive(int n) {
    if (n == 0 || n == 1) {
        return 1;
    }
    return n * factorialRecursive(n - 1);
}

int main() {
    int n;

    printf("Enter a number to calculate its factorial: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 1;
    }

    printf("Factorial using loop: %llu\n", factorialLoop(n));
    printf("Factorial using recursion: %llu\n", factorialRecursive(n));

    return 0;
}

Compile and run the program:

gcc factorial.c -o factorial
./factorial

Example output:

Enter a number to calculate its factorial: 5
Factorial using loop: 120
Factorial using recursion: 120

Key points in this implementation:

  • unsigned long long is used to handle larger factorial values
  • Loop method uses a for loop to multiply numbers
  • Recursive method calls itself with n-1 until base case is reached
  • Error handling for negative numbers is added
  • Both methods produce the same result

Print the Factorial

In this step, you will enhance the factorial calculation program to provide more detailed output and handle different input scenarios. We'll modify the factorial.c file to improve the presentation of factorial results.

Update the factorial.c file:

cd ~/project
nano factorial.c

Replace the previous content with the following improved implementation:

#include <stdio.h>

unsigned long long factorialLoop(int n) {
    unsigned long long result = 1;
    for (int i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

void printFactorialDetails(int n, unsigned long long factorial) {
    printf("Factorial Calculation Details:\n");
    printf("Number (n): %d\n", n);
    printf("Factorial (n!): %llu\n", factorial);

    printf("Factorial Expansion: ");
    for (int i = 1; i <= n; i++) {
        printf("%d%s", i, (i < n) ? " × " : " = ");
    }
    printf("%llu\n", factorial);
}

int main() {
    int n;

    printf("Enter a non-negative integer to calculate its factorial: ");
    scanf("%d", &n);

    if (n < 0) {
        printf("Error: Factorial is not defined for negative numbers.\n");
        return 1;
    }

    if (n > 20) {
        printf("Warning: Factorial for large numbers may cause integer overflow.\n");
    }

    unsigned long long result = factorialLoop(n);
    printFactorialDetails(n, result);

    return 0;
}

Compile and run the program:

gcc factorial.c -o factorial
./factorial

Example output:

Enter a non-negative integer to calculate its factorial: 5
Factorial Calculation Details:
Number (n): 5
Factorial (n!): 120
Factorial Expansion: 1 × 2 × 3 × 4 × 5 = 120

Key improvements in this version:

  • Added a detailed printFactorialDetails() function
  • Displays the full factorial expansion
  • Includes warning for large numbers
  • Provides clear, informative output

Summary

In this lab, you learned how to read an integer input from the user and compute its factorial using both an iterative loop and a recursive function. You explored the process of creating a C program that prompts the user for a number, handles negative inputs, and outputs the factorial result. The lab covered the key steps of reading user input, implementing factorial calculation algorithms, and printing the final result.

Other C Tutorials you may like