Program to find Factorial of a number

Program to find Factorial of a number

 

Consider the following code which finds the factorial of a number using for loop:

CODE:

# include <stdio. h>

# include <conio. h>

void main ()

{

   int fact, j, num;

   fact = 1;

   printf (“Enter the number to find factorial\t”);

   scanf (“%d” , &num);

   for (j = 1; j < = n; j++)

   {

     fact = fact * j;

   }

   printf (“Factorial of %d is %d”, num , fact);

   getch ();

}

OUTPUT:

Enter the number to find factorial 4

Factorial of 4 is 24

 

Program to find factorial of a number using recursion:

Consider the following example in which we are not going to use any looping construct rather we will use recursive function:

CODE:

# include <stdio. h>

# include <conio. h>

int factorial (int num);

void main ()

{

   int fact, j, n;

   printf (“Enter the number to find factorial\t”);

   scanf (“%d”, &num);

   fact = factorial (num);

   printf (“Factorial of %d is %d”, num, fact);

   getch ();

}

int factorial (int num)

{

   int fact = 1;

   if (num == 1)

   {

      return fact;

   }

   else

   {

      fact = num * factorial (num – 1);

      return fact;

   }

}

OUTPUT:

Enter the number to find factorial 4

Factorial of 4 is 24