1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> int main() { int number, i; unsigned long long factorial = 1; // Use unsigned long long for large results // Asking the user to input a positive integer printf("Enter a positive integer: "); scanf("%d", &number); // Factorial of negative numbers doesn't exist if (number < 0) { printf("Factorial of a negative number doesn't exist.\n"); } else { // Calculating factorial for (i = 1; i <= number; ++i) { factorial *= i; // Multiply factorial by i } // Output the result printf("Factorial of %d = %llu\n", number, factorial); } return 0; } |
Explanation:
Returning 0: The program returns 0
to indicate successful execution.cCopy codereturn 0;
Including the standard input-output library: We include the stdio.h
header file so we can use printf
for output and scanf
for input.cCopy code#include <stdio.h>
Main function: The program execution begins with the main()
function.cCopy codeint main() { ... }
Declaring variables:
number
stores the input number.i
is the loop counter used to calculate the factorial.factorial
is initialized to 1 and is used to store the result of the factorial calculation. We useunsigned long long
because the factorial of larger numbers can get very large quickly.
int number, i; unsigned long long factorial = 1;
User input: We prompt the user to input a positive integer using printf
, and scanf
stores the number in the number
variable.cCopy codeprintf("Enter a positive integer: "); scanf("%d", &number);
Checking for negative input: Factorial is not defined for negative numbers. If the user inputs a negative number, the program prints an error message.cCopy codeif (number < 0) { printf("Factorial of a negative number doesn't exist.\n"); }
Calculating the factorial:
- If the input is a positive number or zero (because the factorial of 0 is 1), the program uses a
for
loop to multiply numbers from 1 to the inputnumber
. - For example, if the user enters
5
, the loop will perform:1 * 2 * 3 * 4 * 5
, and store the result infactorial
.
for (i = 1; i <= number; ++i) { factorial *= i; }
Displaying the result: After calculating the factorial, the program prints the result using printf
. The format specifier %llu
is used to print an unsigned long long
integer.cCopy codeprintf("Factorial of %d = %llu\n", number, factorial);
OUTPUT
Enter a positive integer: 5
Factorial of 5 = 120
Enter a positive integer: 0
Factorial of 0 = 1
Enter a positive integer: -3
Factorial of a negative number doesn’t exist.
Summary:
This program checks for negative input, calculates the factorial using a loop, and handles large numbers using unsigned long long
.
The factorial of a number is the product of all positive integers from 1 to that number.
For example, the factorial of 5
is 5! = 5 * 4 * 3 * 2 * 1 = 120
.