C Program to Find Factorial of a Number | Using for loop, while loop & recursion

C Program to Find Factorial of a Number | Using for loop, while loop & recursion

C Program
The Factorial is the product of all numbers, which are less than or equal to that number, and greater than 0.

n! = n * (n-1) * (n -2) * …….* 1

For example, Factorial of 5 is represented as 5! = 5 *4 * 3 * 2 * 1 = 120


C Program to Find Factorial of a Number
Using for loop:

#include <stdio.h>

int main()

{

  int i, Number

  long Factorial = 1;

  printf("Please Enter a number to Find Factorial\n");

  scanf("%d", &Number);

  for (i = 1; i <= Number; i++)

   {

     Factorial = Factorial * i;

   }

  printf("Factorial of %d = %d ", Number, Factorial);

  return 0;

}


Using while loop:

#include <stdio.h>

int main()

{

  int Number, i = 1

  long Factorial = 1;

  printf("Please Enter a number to Find Factorial\n");

  scanf("%d", &Number);

  while (i <= Number)

   {

     Factorial = Factorial * i;

     i++;

   }

  printf("Factorial of %d = %d ", Number, Factorial);

  return 0;

}


Using recursion:

#include <stdio.h>

long Calculate_Factorial(int Number)

  if (Number == 0 || Number == 1)  

    return 1;  

  else

    return Number * Calculate_Factorial (Number -1);

int main()

{

 int Number

 long Factorial = 1

 printf("Please Enter a number to Find Factorial\n");

 scanf("%d", &Number);

 Factorial = Calculate_Factorial(Number);

 printf("Factorial of %d = %d ", Number, Factorial);

 return 0;

}


Output:

Please Enter a number to Find Factorial 5

Factorial of 5 = 120

Please Enter a number to Find Factorial 10

Factorial of 10 = 3628800


Run Code: If you want run this code copy this code, paste here and run.

No comments: