C Language Example - Factorial
The factorial of a positive integer (English: factorial) is the product of all positive integers less than or equal to that number, and the factorial of 0 is 1. The factorial of a natural number n is written asn!。
n!=1×2×3×...×nThe factorial can also be defined recursively:0!=1,1!=1,n!=(n-1)!×n。
Example
#include <stdio.h>
int main()
{
int n, i;
unsigned long long factorial = 1;
printf("Enter an integer:");
scanf("%d",&n);
// If the input is a negative number, display an error
if (n < 0)
printf("Error! Negative numbers have no factorial jiechen");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("%d! = %llu", n, factorial);
}
return 0;
}
Run result:
输入一个整数: 10 10! = 3628800
Example - Using Recursion
#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter an integer:");
scanf("%d", &n);
printf("%d! = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n > 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
C Language Examples