In this example, we will calculate the factorial of a number taking the value from the user in C.
Before we begin, you should have the knowledge of the following in C Programming:
Factorial of n number: Factorial of n number is the product of all the positive descending integers and is denoted by n!.
Example:
factorial of n (n!) = n * (n-1) * (n-2) * (n-3)….1
factorial of 5 (n!) = 5 * 4 * 3 * 2 * 1
NOTE: Factorial of 0 (0!) = 1
In this tutorial, we will see various ways to find the factorial of a number in C.
1. Factorial Program in C using Function with return.
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 29 30 31 | #include <stdio.h> int factorial(int); int main() { int num, fact = 1, result; //user input printf("Enter the number to find factorial: "); scanf("%d", &num); result = factorial(num); //function call //display printf("Factorial of %d is: %d\n", num, result); getch(); return 0; } //function to find factorial int factorial(int num) { int i, fact = 1; //factorial calculation for (i = 1; i <= num; i++) fact = fact * i; return (fact); } |
Output:
Enter the number to find factorial: 5
Factorial of 5 is: 120
2. C program to find factorial of a number using Ternary operator with recusrion
The following program uses the recursion technique along with the Ternary operator. Also, the program does not declare the function prototype at first like the previous because the function is defined before the main() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <stdio.h> int factorial(int n) { // using ternary operator with recursion return (n == 1 || n == 0) ? 1 : n* factorial(n - 1); } int main() { int num, result; //taking Inputs printf("Enter the number to find factorial: "); scanf("%d", &num); //function call and display the result result = factorial(num); printf("Factorial of %d is: %d\n", num, result); getch(); return 0; } |
Output:
Enter the number to find factorial: 5
Factorial of 5 is: 120