C Program to Find Factorial of a Number
For any positive number n, its factorial is given by:
You must know that if a number is negative, factorial does not exist and the factorial of 0 is 1.
This program takes an integer as an input from a 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.It may be noted that in summation problems the initial value of the variable sum must be equal to zero(0).But in this case since successive multiplications are used the initial value of the variable that holds the factorial value,say fact,must be 1.A loop control variable like i itself i used for counting as well as the next term.The statement of the type fact=fact*i is used to get the required factorial.
factorial = 1*2*3*4....n
You must know that if a number is negative, factorial does not exist and the factorial of 0 is 1.
This program takes an integer as an input from a 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.It may be noted that in summation problems the initial value of the variable sum must be equal to zero(0).But in this case since successive multiplications are used the initial value of the variable that holds the factorial value,say fact,must be 1.A loop control variable like i itself i used for counting as well as the next term.The statement of the type fact=fact*i is used to get the required factorial.
Source Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | /* C program to display factorial of an integer if user enters non-negative integer. */ #include<stdio.h> int main() { int n,i,fact=1; printf("Enter the number:\n"); scanf("%d",&n); if(n<0) { printf("Sorry ! Factorial of negative number doesn't exist.\n"); } else{ for(i=1;i<=n;++i) /* for loop terminates if i>n */ { fact=fact*i; } printf("The value of the factorial is %d",fact); } return 0; } |
Output 1-
Enter an integer: -5
Sorry ! Factorial of negative number doesn't exist..
Output 2-
Enter the number: 5
Factorial = 120
ReplyDeleteVery informative article.Thank you author for posting this kind of article .
http://www.wikitechy.com/view-article/c-program-to-find-factorial-of-a-number-with-example-and-explanation
Both are really good,
Cheers,
Venkat