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.
- Function Declaration (
int factorial(int n)
): A function named
factorial
is declared, which takes an integer parametern
and returns an integer. This function is later defined to calculate the factorial of a number.Factorial Calculation (
int factorial(int n) { ... }
):The
factorial
function is defined using recursion to calculate the factorial of a number. The base case is whenn
is 0 or 1, in which case the function returns 1. Otherwise, it recursively calls itself withn - 1
and multiplies the result byn
.Main Function (
int main() { ... }
):The
main
function is the entry point of the program.Variable Declaration (
int num;
):An integer variable
num
is declared to store the user input.User Input (
printf("Enter a non-negative integer: ");
andscanf("%d", &num);
):The user is prompted to enter a non-negative integer, and the entered value is read using
scanf
and stored in the variablenum
.Input Validation (
if (num < 0) { ... }
):Checks if the entered number is non-negative. If it's negative, a message is printed, and the program exits.
Factorial Calculation and Output (
int result = factorial(num);
andprintf("The factorial of %d is: %d\n", num, result);
):If the entered number is non-negative, the
factorial
function is called with the user input, and the result is stored in the variableresult
. The program then prints the calculated factorial.Return Statement (
return 0;
):- The
main
function returns 0 to indicate successful execution to the operating system.