Friday, 1 August 2014

Factorial of a Number

Factorial of a Number

Factorial of any number is the product of an integer and all the integers below it for example factorial of 4 is
4! = 4 * 3 * 2 * 1 = 24

Factorial of a Given Number using for Loop

/************************************************
   Factorial of Number
**************************************************/

#include< stdio.h>
#include< conio.h>
void main()
{
int i, no, fact=1;
clrscr();
printf("Enter the any no. : ");
scanf("%d",&no);
for(i=1;i< =no;i++)
{
fact=fact*i;
}
printf("Factorial =%d ",fact);
getch();
}
Output
Enter the any no. : 4
Factorial = 24

Factorial of a Given Number using Do-While Loop

/***************************************************
               Factorial of Number
****************************************************/
#include< stdio.h>
#include< conio.h>

 void main()
  {
   long n, i, fact=1;
   clrscr();
   printf("Enter any number = ");
   scanf("%ld",&n);
   i=n;
   if(n>=0)
    {
   do
    {
    fact=fact*i;
    i--;
    }
   while(i>0);
   printf("\nFactorial = %ld",fact);
   }
   else
    {
   printf("fact on -ve no is not possible");
    }
   getch();
  }
Output
Enter the any no. : 5
Factorial = 120

Factorial of Number Using Recursion

/***************************************************************
               Factorial of Number
***************************************************************/

#include< stdio.h>
#include< conio.h>
void main()
{
int fact(int);
int f, n;
clrscr();
printf("ENTER ANY NUMBER = ");
scanf("%d",&n);
f=fact(n);
printf("\n\nFACTORIAL OF %d IS = %d",n,f);
getch();
}
int fact(int a)
{
if(a==1)
return(1);
else
{
return(a*fact(a-1));
}
}
Output
Enter the any no. : 6
Factorial = 720

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...