## Introduction

In this program, you will learn to calculate the factorial of a number.

The user will enter a particular value, and then through this program, we will compute its factorial.

For example, **Factorial of 5** is (**!** is the symbol for factorial):

5! =5*4*3*2*1=120

Similarly, **Factorial of 7 **is

7! =7*6*5*4*3*2*1=5040

Factorial of negative numbers doesn’t exist.

Factorial of 0 and 1 is 1.

What is the use of this program?

It is easy to calculate the factorial up to certain values, but it is difficult to calculate factorial like **100! **,** 500!** etc. A small code written in C will make this task quite easy.

To understand this example, you should know about the following C programming topics:

1. C data types

2. Operators in C

3. Recursion

4. C user-defined functions

**Recursion is the process in which a function calls itself.**

## Program

#include<stdio.h> int factorial(int x) { if(x==0) { return 1; } else { return x*factorial(x-1); // recursion } } int main() { int a; printf("Enter an integer:\n"); scanf("%d",&a); if (a>=0) // condition to check either a is a positive integer or 0 { int fact=factorial(a); printf("Factorial of %d is %d",a,fact); } else // when ‘a’ is a negative number { printf("Factorial does not exist"); } return 0; }

## Output

## Explanation

In the above program, we have to calculate the factorial of ‘x’.

If ‘a’ is a positive number only then we will proceed with the ‘factorial’ function else print ‘a’ is a negative number.

In the definition of the ‘factorial’ function, we have used the recursion process in the ‘else’ statement.

**return x*factorial(x-1); **

The above statement uses recursion and calculates the factorial of the value entered by the user.

## 0 Comments