C Online Compiler
Example: Factorial using Recursion in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Factorial using Recursion #include <stdio.h> // Function to calculate factorial using recursion long long factorial(int n) { // Step 1: Define the base case // Factorial of 0 is 1 if (n == 0) { return 1; } // Step 2: Define the recursive step // n! = n * (n-1)! else { return (long long)n * factorial(n - 1); } } int main() { int num; long long result; // Step 1: Prompt the user for input printf("Enter a non-negative integer: "); scanf("%d", &num); // Step 2: Validate input if (num < 0) { printf("Factorial is not defined for negative numbers.\n"); } else { // Step 3: Call the recursive factorial function result = factorial(num); // Step 4: Display the result printf("Factorial of %d = %lld\n", num, result); } return 0; }
Output
Clear
ADVERTISEMENTS