Write a C Program to find factorial of number

C Program to find Factorial of Number

Factorial Definition: In mathematics, the factorial of a non-negative integer ‘n,’ denoted by ‘n!,’ is the product of all positive integers less than or equal to ‘n.’ It is defined as:

n!=n×(n−1)×(n−2)×…×3×2×1

For example: 5!=5×4×3×2×1=120

Factorials are often used in combinatorics, probability, and other areas of mathematics.

Explanation:

Header Files: We include the standard input-output library (stdio.h) to use functions like printf and scanf.

Function Prototype: We declare a function prototype for the factorial function to inform the compiler about the

function’s signature before using it in the main function.

Main Function:

  • We declare a variable num to store the user’s input.
  • We prompt the user to enter a non-negative integer.
  • We use scanf to read the user’s input.
  • We check if the input is non-negative. If it is, we calculate and display the factorial using the factorial function. If
  • it’s negative, we print an error message.

Factorial Function:

  • This function takes an integer n as an argument and returns an unsigned long long integer.
  • It uses recursion to calculate the factorial.
  • The base case is when n is 0 or 1, in which case the factorial is 1.
  • The recursive case multiplies n by the factorial of (n-1).

Here’s a simple C program to calculate the factorial of a number:

Program:

#include<stdio.h> 
int main() 
{ 
int i,fact,number; 
printf("Enter a number: "); 
scanf("%d",&num); 
for(i=1,fact=1;i<=num;i++){ or (for(i=num,fact=1;i<=1;i--))
fact=fact*i; 
} 
printf("Factorial of %d is: %d",num,fact); 
return 0; 
} 

Output: Enter a number: 9 Factorial of 9 is: 362880

Conclusion:
This C program demonstrates a simple way to calculate the factorial of a non-negative integer using recursion. The program handles non-negative input and provides informative messages for negative input. Understanding this program helps in learning basic input/output operations, function usage, and recursion in C programming.

Scroll to Top