C PROGRAMMING LANGUAGE(example)

 EXAMPLE


Here is a basic example of a C program that uses a recursive function to get the factorial of a given number:


#include <stdio.h>


// Function to calculate the factorial recursively

int factorial(int n) {

    if (n == 0 || n == 1) {

        return 1;

    } else {

        return n * factorial(n - 1);

    }

}


int main() {

    int num;

    

    // Prompt user to enter a number

    printf("Enter a positive integer: ");

    scanf("%d", &num);

    

    // Check if the number is non-negative

    if (num < 0) {

        printf("Factorial of a negative number is undefined.\n");

    } else {

        // Calculate and print the factorial

        printf("Factorial of %d = %d\n", num, factorial(num));

    }

    

    return 0;

}




Comments