Factorial Program in C

Factorial of a number is a mathematical expression. First you need to understand how does the factorial number comes for a given number, then by using the same principle I will help you write the Factorial Program in C.

I am writing all of my programs for beginners. If you already know the basics of a problem then you can directly jump to the C program.

Factorial of a Number

Factorial of a number ‘n’ is represented as n!

The factorial number for a given number ‘n’ is a multiplication of all numbers starting from 1 to n.

For example, I want to find the factorial of a number 4, so ‘n’ is 4 here.

So, 4! = 1 * 2 * 3 * 4

or it will be same as 4! = 4 * 3 * 2 * 1

We can program starting from 1 to n or n to 1 either way.

It is the same principle for all numbers.

NOTE:
We can not find factorial for the number 0. So, in our C program for factorial, we have to handle this case as well.

Writing the Factorial Program in C

To be able to understand this problem you must already know the below things in C:

  • C datatypes
  • C Conditional statement (if else or just true or false checking)
  • Loop in C
  • Function Recursion (optional)

First, let’s prepare the whole program starting from getting the number from user input step-by-step as below:

  • Take the number from the user
  • Store the number in an int variable
  • Check if the user has entered a valid number or not
  • Loop through the number to get the factorial of that number
  • Exit from the loop if we have multiplied the number till 1 (in descending order from the input number that we have taken)
  • Print the factorial of that number on the output

Declare all required variables

As the C language’s variable declaration rules go, we have to declare all the required variables to store several data at the beginning of the program.

Let’s see what variables we need:

  • to store user input number
  • to store the final factorial output number
  • an iteration counter number for the ‘for’ loop (not necessary for certain cases)

Let’s declare all the variables:

int user_num;
int factorial = 1;
int i = 1;

‘factorial’ variable is initialized to 1 because we will start multiplying from the number 1 and go all the way till the number given by the user.

Take the number from the user

we use scanf() function to accomplish this.

scanf ("%d", &user_num);Code language: JavaScript (javascript)

But how does the user know when he has to give that number.

To make it clear, we need to add a proper print statement asking the user to enter a number.

printf ("Enter a number to find factorial of:\n");
scanf ("%d", &user_num);Code language: JavaScript (javascript)

Now, the user entered number is in ‘number’ variable.

Verify user input

It is important to first to all error checking to make sure the input we have received is good to go ahead to work with.

As I have already mentioned, we cannot find factorial for neither 0 nor any negative number.

So, we will check for the same thing with the user input number which is stored in ‘user_num’ variable.

// shows error if the user enters a negative integer
if (user_num <= 0)
{
    printf ("User entered number is either 0 or negative. This cannot be used to find factorial.\n");
    return -1;
}Code language: JavaScript (javascript)

Find factorial of a number

Now, that we know that this is a positive number, we have several methods to find the factorial of the number.

Let’s take a look at the below codes.

Factorial of a number using ascending ‘for loop’

We use a for loop either in an ascending order or in a descending order to find the factorial of the user input number.

// a new number is taken to loop through
i = 0;

for (i = 1; i <= user_num; i++)
{
    factorial = (factorial * i);
}Code language: JavaScript (javascript)

Explanation:

Let’s say the user has entered a number of 3. So, user_num will have the value 3.

Using the for loop, we will repeatedly loop from i = 1 to 3 because of this statement i <= user_num

For each time we will loop through, we will multiply the value of factorial with the number 1 which goes incrementing each time.

So, the loop will produce the below result:

  • 1st iteration factorial = 1 and i = 1, so factorial = factorial * 1 will be 1
  • 2nd iteration factorial (=1) * i (=2). So, the final factorial value will be 2
  • 3rd iteration factorial (=2) * i (=3). So, the final value of factorial variable will be 6
  • On the fourth iteration ‘i’ will be 4 so the condition ‘i <= user_num‘ will not be true and it will come out of the loop.
Optimization

For the number ‘n’ given by the user, the for loop will iterate that many times to calculate the answer.

No more extra space required to calculate each time. We only require space once.

So, time complexity will be O(n)

Space complexity will be O(1)

Factorial of a number using a ‘While loop’

The same result we can get it by using a while loop and decrementing the user input value

while ( user_num > 1 )
{
    factorial = (factorial * user_num);
    user_num--;
}Code language: JavaScript (javascript)

Assuming the user input value is 3, let’s see how does the whole iteration will go.

Explanation:

  • 1st iteration, user_num is true as it has the value 3. Inside the loop we will have this calculation: factorial (=1) * user_num (=3). So, factorial variable will be stored with the value 3.
  • 2nd iteration, factorial (=3) * user_num (=2). Factorial variable will be stored with value 3 * 2 equals to 6.
  • 3rd iteration user_num (=1) which is not greater than 1. So, we will come out of the loop.
Optimization

For the number ‘n’ given by the user, the while loop will iterate (that many times – 1) to calculate the answer.

No more extra space required to calculate each time. We only require space once.

So, time complexity will be O(n-1)

Space complexity will be O(1)

Factorial of a Number using Function Recursion

This is a little complex for beginner to understand but I will try to make it as simple as possible while explaining.

In this case, we will have to define a function let’s say we name it calculate_factorial () which will take the number for which it has to calculate the factorial.

This function we will call it from main () function like this:

calculate_factorial (3);

Now let’s take a look what will be the function definition of calculate_factorial () which will calculate recursively.

calculate_factorial (int input)
{
    int factorial;

    if (input == 1)
    {
        return 1;
    }

    return input * calculate_factorial ( --input );
}Code language: JavaScript (javascript)

Explanation:

You have to visualize how will this same function will be executed for a given number let’s say 3.

Let me expand this whole function how will this execute when we get an input number of 3:

calculate_factorial (int 3 )
{
    int factorial;

    /* This will not be true for the input value of 3 */
    if (input == 1)
    {
        return 1;
    }

    return 3 * calculate_factorial ( --3 );

        calculate_factorial ( 2 );
        {
            return 2 * calculate_factorial ( --2 );
        }

            calculate_factorial ( 1);
            {
                if (input == 1)
                {
                     return 1;
                }
            }

}Code language: JavaScript (javascript)

So, when we return from the last function our values will be like this:

  • calculate_factorial ( 1 ); function will return 1.

If I will re-write the recursive function it will be expanded like this:

return 3 * calculate_factorial ( --3 )Code language: JavaScript (javascript)
return 3 * 2 * calculate_factorial ( --2 ) Code language: JavaScript (javascript)
return 3 * 2 * calculate_factorial ( 1 ) Code language: JavaScript (javascript)
return 3 * 2 * return 1Code language: JavaScript (javascript)

So, the final expression of the whole recursive function will be like this:

return 3 * 2 * 1Code language: JavaScript (javascript)

For a value 3 we will get the factorial value as 6.

Optimization

For the number ‘n’ given by the user, the function will be called that many times to calculate the answer.

This means, the same function will be pushed that many times on the stack and it will be using space or size for local variables that many times.

So, time complexity will be O(n)

Space complexity will be O(n)

Final C Program to find Factorial

I have explained in 3 ways as below:

  1. Using for loop
  2. Using while loop
  3. Using function recursion

Complete Factorial Program in C using For loop

#include <stdio.h>

int main ()
{
    int user_num;
    int factorial = 1;
    int i = 1;

    printf ("Enter a number to find factorial of:\n");
    scanf ("%d", &user_num);

    // shows error if the user enters a negative integer
    if (user_num <= 0)
    {
        printf ("User entered number is either 0 or negative. This cannot be used to find factorial.\n");
        return -1;
    }

    /* Calculate factorial number using for loop for the given number */
    for (i = 1; i <=user_num; i++)
    {
        factorial = (factorial * i);
    }

    printf ( "Factorial of %d is %d\n", user_num, factorial );

    return 0;
}Code language: PHP (php)

Complete Factorial Program in C using While loop

#include <stdio.h>

int main ()
{
    int user_num;
    int factorial = 1;

    printf ("Enter a number to find factorial of:\n");
    scanf ("%d", &user_num);

    // shows error if the user enters a negative integer
    if (user_num <= 0)
    {
        printf ("User entered number is either 0 or negative. This cannot be used to find factorial.\n");
        return -1;
    }

    /* Calculate factorial number using while loop for the given number */
    while ( user_num > 1 )
    {
        factorial = (factorial * user_num);
        user_num--;
    }

    printf ( "Factorial of %d is %d\n", user_num, factorial );

    return 0;
}Code language: PHP (php)

Complete Factorial Program in C using Function Recursion

#include <stdio.h>

int main ()
{
    int user_num;
    int final_factorial;

    printf ("Enter a number to find factorial of:\n");
    scanf ("%d", &user_num);

    // shows error if the user enters a negative integer
    if (user_num <= 0)
    {
        printf ("User entered number is either 0 or negative. This cannot be used to find factorial.\n");
        return -1;
    }

    /* Calculate factorial number using function recursion */
    final_factorial = calculate_factorial ( user_num );

    printf ( "Factorial of %d is %d\n", user_num, final_factorial );

    return 0;
}

calculate_factorial (int input)
{
    int factorial;

    if (input == 1)
    {
        return 1;
    }

    return input * calculate_factorial ( --input );
}Code language: PHP (php)

Conclusion

This does not teach you finding the factorial of a number. We are definitely not here to learn Mathematics, are we?

Through the factorial program in C you would learn the following:

  • for loop in C
  • while loop in C
  • function recursion in C
  • reading and storing a variable in C
  • printing a variable in C
  • creating a function in C

If you have not learned any one of these, then please go back and identify where have you missed. If you still could not find it by yourself please message me in the comment box and I will try to help you out.

If you have learned something more than what I have listed above, please comment and let me know.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.