Monday, September 23, 2013

C Program to find Factorial of a number

C Program to find Factorial of a number

For any positive number n, its factorial is given by:

Factorial = 1*2*3*4....n


If a number is negative, factorial doesn’t exist and factorial of 0 is 1

This program takes an integer from user, If user enters negative integer, this program will display error message and if user enters non-negative integer, this program will display the factorial of that number.

Source code to find factorial of a number:

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
 int n, count,  int factorial=1;
 printf("Enter an integer: ");
 scanf("%d",&n);
 if ( n< 0)
printf("Error!!! Factorial of negative number doesn't exist.");
 else
 {
 for(count=1;count<=n;++count)                  /* for loop terminates if count>n */
   {
         factorial*=count;                                /* factorial=factorial*count */
   }

 printf("Factorial = %d",factorial);
 }
 getch();
}

Output 1:
Enter and Integer: -5
Error!!! Factorial of negative number doesn't exist.

OUTPUT2:

Enter and Integer: 10
Factorial= 3628800

No comments:

Post a Comment