C Program Code to Find Factorial number
Detailed Explanation
- Include the Standard I/O Library:
#include <stdio.h>
is used to include the Standard Input/Output library. This allows the program to use functions like printf
and scanf
for displaying output and reading input.
- Define the Factorial Function:
int factorial(int n)
is a function that calculates the factorial of a number n
.
- The factorial of a number
n
is the product of all positive integers up to n
. For example, the factorial of 5 (denoted as 5!) is 5 * 4 * 3 * 2 * 1 = 120
.
- The function uses recursion, which means it calls itself with a smaller value each time.
- The base case is when
n
is 0. The factorial of 0 is defined as 1.
- If
n
is greater than 0, the function returns n
multiplied by the factorial of n - 1
.
- Main Function:
- The
main
function is the entry point of the program.
int number;
declares a variable to store the user’s input.
printf("Enter a number: ");
prompts the user to enter a number.
scanf("%d", &number);
reads the number input by the user and stores it in the number
variable.
int result = factorial(number);
calculates the factorial of the entered number by calling the factorial
function.
printf("Factorial of %d is %d\n", number, result);
prints the result to the screen.
return 0;
indicates that the program has executed successfully.
How to Use This Code
- Copy the Code:
- Copy the C program code provided above.
- Create a C File:
- Open a text editor and paste the code into a new file. Save the file with a
.c
extension, such as factorial.c
.
- Compile the Code:
- Use a C compiler to compile the code. If you’re using GCC, you can compile the program with:
gcc factorial.c -o factorial
- This command creates an executable file named
factorial
.
- Run the Program:
- Execute the compiled program from the command line:
- The program will prompt you to enter a number. Type a number and press Enter.
- View the Result:
- The program will calculate and display the factorial of the number you entered.
Example Output
If you enter the number 5
, the output will be:
Enter a number: 5
Factorial of 5 is 120
C Program Code
#include
// Function to calculate the factorial of a number
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
int main() {
int number;
// Ask the user to input a number
printf("Enter a number: ");
scanf("%d", &number);
// Calculate the factorial
int result = factorial(number);
// Display the result
printf("Factorial of %d is %d\n", number, result);
return 0;
}
Compiled Code