Factorial Program in C Using Function

Here we will write a factorial program in C using the function. Previously we have already written a factorial program only using loops.

Factorial of a number N is given as the product of every whole number from 1 to N. For example:-
Factorial of 5 = 1*2*3*4*5 = 120
or,
Factorial of 6 = 6*5*4*3*2*1 = 720

To calculate the factorial of a number we will use loops to execute the same logic multiple times. In this program, we will use a user define function to calculate the factorial of the number.

Prerequisites for this program:- Introduction to Function in C, User-defined Functions in C, C Program Using Functions Example

The factorial of a negative number is not possible through this program. First, we should check the number is positive or negative. If the number is positive then only we will calculate the factorial of the number.

Factorial program using a function in C

#include<stdio.h>
int isNegative(int n);
long factorial(int n);

// main function
int main()
{
  int num;
  long result;

  printf("Enter a number: ");
  scanf("%d",&num);

  if(isNegative(num))
  {
    printf("%d is a negative number.\n",num);
    printf("Factorial of %d is not possible.\n", num);
  }

  else
  {
    result = factorial(num);
    printf("Factorial of %d = %ld", num, result);
  }

  return 0;
}

// function to check number is positive number or negative number
int isNegative(int n)
{
  if(n>0) return 0;
  else return 1;
}

// function to calculate factorial of the number
long factorial(int n)
{
  long fact=1;
  for(int i=n; i>=1; i--)
  {
    fact *= i;
  }
  return fact;
}

Output for the different test-cases:-

Enter a number: 5
Factorial of 5 = 120

Enter a number: 10
Factorial of 10 = 3628800

The user-defined function factorial calculates the factorial of a number. Inside this function, one local variable fact is defined and initialized with value 1. Using for loop the factorial value is calculated and stored in the variable fact, and later result is returned to the caller function. Finally, the result is displayed to the screen from the main function.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply