Finding Factorial Using Recursion

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to find the factorial of a given number using recursion in C programming language. Factorial is denoted by '!' and is a product of all positive integers that are less than or equal to the given number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.

Initialize the main() function

In the main function, we will declare variables to store the inputted value and the calculated factorial. We will then prompt the user to input a value for which the factorial will be found.

#include <stdio.h>

int main()
{
    int num, factorial;
    printf("Enter a number: ");
    scanf("%d", &num);
}

Create the function to calculate factorial using recursion

We will now create a function named 'factorial' that takes an integer parameter 'num' and returns an integer value. In this function, we will use recursion to calculate the factorial of the given number. If the value of the given number is equal to 1 or 0, we will return 1 as the factorial of both values is 1. If the given number is greater than 1, we will calculate its factorial using recursion and return the value.

int factorial(int num)
{
    if(num == 0 || num == 1)
    {
        return 1;
    }
    else
    {
        return num * factorial(num-1);
    }
}

Call the factorial function in the main function and print the result

We will now call the 'factorial' function inside the 'main' function and pass the inputted value as the parameter. We will then store the returned value in the 'factorial' variable and print the result to the console.

#include <stdio.h>

int factorial(int num);

int main()
{
    int num, factorial;
    printf("Enter a number: ");
    scanf("%d", &num);

    factorial = fact(num);
    printf("Factorial of %d is %d", num, factorial);

    return 0;
}

Compile and run the program

Now that the program has been written, save the file as 'main.c' in the '~/project/' directory. Open the terminal and navigate to the directory containing the 'main.c' file. Use the following command to compile the program:

gcc main.c -o main

Once the program has been compiled successfully, use the following command to run the program:

./main

Full code of 'main.c'

Use this code as a reference if necessary.

#include <stdio.h>

int factorial(int num);

int main()
{
    int num, factorial;
    printf("Enter a number: ");
    scanf("%d", &num);

    factorial = factorial(num);
    printf("Factorial of %d is %d", num, factorial);

    return 0;
}

int factorial(int num)
{
    if(num == 0 || num == 1)
    {
        return 1;
    }
    else
    {
        return num * factorial(num-1);
    }
}

Summary

In this lab, we learned how to calculate the factorial of a given number using recursion in C. We created a function that uses recursion to find the factorial and a main function to input a number and call the factorial function.

Other C Tutorials you may like