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 or 1 is 1 if (n == 0 || n == 1) { return 1; } // Step 2: Define the recursive step // n! = n * (n-1)! else { return n * factorial(n - 1); } } int main() { int num; long long result; // Step 3: Prompt user for input printf("Enter a non-negative integer: "); scanf("%d", &num); // Step 4: Validate input if (num < 0) { printf("Factorial is not defined for negative numbers.\n"); } else { // Step 5: Call the recursive function result = factorial(num); // Step 6: Display the result printf("Factorial of %d = %lld\n", num, result); } return 0; }
Output
Clear
ADVERTISEMENTS