In this step, we will write the C code to calculate the factorial of a number. We'll create a function to handle the factorial calculation using recursion, which is a common approach for this type of mathematical problem.
#include <stdio.h> // Function to calculate factorial recursively unsigned long long factorial(int n) { if (n == 0) // Base case return 1; else return n * factorial(n - 1); // Recursive case } int main() { int number; printf("Enter a positive integer: "); scanf("%d", &number); if (number < 0) printf("Factorial of a negative number doesn't exist.\n"); else printf("Factorial of %d = %llu", number, factorial(number)); return 0; }
This program prompts the user for a positive integer, then calculates and displays its factorial. The function factorial
is a recursive function that multiplies the number by the factorial of the number minus one, continuing until it reaches zero, where it returns 1.