Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Write a program that asks the user to enter a number and then calculates and prints its factorial.

C
``````#include <stdio.h>

int main() {
int number, factorial = 1;

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

if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (int i = 1; i <= number; i++) {
factorial *= i;
}

printf("The factorial of %d is %d\n", number, factorial);
}

return 0;
}``````

Explanation:

• When you run this program, it will prompt the user to enter a number.
• After the user inputs the number, the program will calculate its factorial using a for loop.
• If the number is negative, it will display a message stating that factorial is not defined for negative numbers.
• Otherwise, it will display the calculated factorial.
• In this program, we declare two variables number and factorial of type int.
• We use printf() to display the prompt message and scanf() to read the user input.
• The factorial is calculated using a for loop that iterates from 1 to the given number and multiplies each number to the factorial variable.
• Finally, we use printf() to display the number and its factorial.
• If the number is negative, we display a message indicating that the factorial is not defined.

Output:

C
``````Enter a number: 4
The factorial of 4 is 24``````