Before we start coding lets have a brief look on what factorial really means.?
The factorial of a integer n is nothing but the product of the integer and all the integer below it.
For example n!=(n)*(n-1)*(n-2)...*2*1
or, n!=1*2*3*4....(n-1)*n
note that 0!=1
The factorial of a integer n is nothing but the product of the integer and all the integer below it.
For example n!=(n)*(n-1)*(n-2)...*2*1
or, n!=1*2*3*4....(n-1)*n
note that 0!=1
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 26 27 28 | #include<stdio.h> void main() { int i, num; int factorial; printf("Enter the integer :\n"); scanf("%d",&num); if(num > 0) { for(i = 1; i <= num; i++) { factorial = factorial * i; } printf("The factorial of %d is %d",num,factorial); } else if(num == 0) { printf("The factorial of %d is 1",num,factorial); //0! is always 1 } else { printf("Error! Negative number's factorial doesnt exist. Enter a positive number:\n"); //error message for user for entering negavitive number } } |
OUTPUT
Explanation
Within the main function first we declared three integer variable i , n and factorial . Next we display a message to take input from the user and store it to the integer variable n.Next we use a if -else conditional checking that will check the number as positive or negative. If the number is negative then it will display a message that "Error! Negative number's factorial doesn't exist. Enter a positive number:".And if the number is positive it will continue.Then under the for loop it will multiply number and numbers below it one by one and store it in factorial integer variable.when the controls comes out of the loop then it will display it.
I
I
Related Topics
- C program to display Fibonacci series up to n terms
- C Program to display Fibonacci series up to a certain number
- C Program to find prime numbers between intervals using function.
- C Program to check whether a number is perfect or not
- C program to identify a number as Even or Odd
- C program to print "Hello World"
No comments:
Post a Comment