c online compiler

#include <stdio.h>

// Function to calculate the factorial of a number
int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

// Main function
int main() {
    // Declare variables
    int num;

    // Prompt user for input
    printf("Enter a non-negative integer: ");

    // Read user input
    scanf("%d", &num);

    // Check if the entered number is non-negative
    if (num < 0) {
        printf("Please enter a non-negative integer.\n");
    } else {
        // Calculate and display the factorial
        int result = factorial(num);
        printf("The factorial of %d is: %d\n", num, result);
    }

    // Return 0 to indicate successful execution
    return 0;
}

Explanation: 1. Include Header File (#include <stdio.h>): - The #include preprocessor directive is used to include the standard input-output header file (stdio.h), which is necessary for input and output operations.

  1. Function Declaration (int factorial(int n)):
  2. A function named factorial is declared, which takes an integer parameter n and returns an integer. This function is later defined to calculate the factorial of a number.

  3. Factorial Calculation (int factorial(int n) { ... }):

  4. The factorial function is defined using recursion to calculate the factorial of a number. The base case is when n is 0 or 1, in which case the function returns 1. Otherwise, it recursively calls itself with n - 1 and multiplies the result by n.

  5. Main Function (int main() { ... }):

  6. The main function is the entry point of the program.

  7. Variable Declaration (int num;):

  8. An integer variable num is declared to store the user input.

  9. User Input (printf("Enter a non-negative integer: "); and scanf("%d", &num);):

  10. The user is prompted to enter a non-negative integer, and the entered value is read using scanf and stored in the variable num.

  11. Input Validation (if (num < 0) { ... }):

  12. Checks if the entered number is non-negative. If it's negative, a message is printed, and the program exits.

  13. Factorial Calculation and Output (int result = factorial(num); and printf("The factorial of %d is: %d\n", num, result);):

  14. If the entered number is non-negative, the factorial function is called with the user input, and the result is stored in the variable result. The program then prints the calculated factorial.

  15. Return Statement (return 0;):

  16. The main function returns 0 to indicate successful execution to the operating system.