Factorial of a Number (Recursive Function)

Algorithm

Step 1: Start

Step 2: Define a recursive function `factorial(n)`

Step 3: Base case - if `n` is 0, return 1

Step 4: Recursive case - return `n * factorial(n-1)`

Step 5: In `main()`, take input for the number

Step 6: Call `factorial(number)` and store the result

Step 7: Print the factorial

Step 8: End

Flowchart

graph TD; A([Start]) --> H["Recursive Function
factorial"]; H --> B[/Input Number/]; B --> C{Check if n == 0}; C --> |Yes| D[Return 1]; C --> |No| E["Return n * factorial(n - 1)"]; D --> F[/Output Factorial/]; E --> F; F --> G([End]); classDef start_end fill:#00cc44,stroke:#006622,stroke-width:2px,color:#ffffff; classDef input_output fill:#ffdd44,stroke:#cc9900,stroke-width:2px,color:#000000; classDef process fill:#4488ff,stroke:#0044cc,stroke-width:2px,color:#ffffff; classDef decision fill:#ff8844,stroke:#cc4400,stroke-width:2px,color:#ffffff; class A,G start_end; class B,F input_output; class C decision; class H,E,D process;

Program

/* C Program: Factorial using Recursion */
#include<stdio.h>

long factorial(int n) {
    if (n == 0)
        return 1;
    else
        return (n * factorial(n - 1));
}

int main() {
    int number;
    long fact;

    printf("Enter a number: ");
    scanf("%d", &number);

    fact = factorial(number);

    printf("Factorial of %d is %ld\n", number, fact);

    return 0;
}