C

C Program To Find Factorial Of a Number Using Recursion

In this tutorial, we are going to see how to write a C program to find the factorial of a number using recursion. The factorial of a number is the product of all integers between 1 and itself. There are four ways to find a factorial of a given number, by using for loop, while loop, recursion, or by creating a function on a range from 1 to X(user entered number). Remember that the end value must be the number entered by the user + 1.
 

 

C Program To Find Factorial Of a Number Using Recursion
#include <stdio.h>
 
long factorial(int n)
{
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1));
}
 
int main()
{
  int nbr;
  long fact;
 
  printf("Enter a number to calculate its factorial: ");
  scanf("%d", &nbr);
 
  if (nbr < 0)
    printf("The factorial of negative integers is not defined.\n");
  else
  {
    fact = factorial(nbr);
    printf("%d! = %ld\n", nbr, fact);
  }
 
  return 0;
}

Output:

Enter a number to calculate its factorial: 3
3! = 6

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *