ADVERTISEMENT
Factorial of A Number
This code calculates the factorial of a number provided by the user by iterating through a for loop and continuously multiplying the running factorial value by the loop variable i. The result is displayed as number! = factorial.
#include<stdio.h>
main()
{
int number,factorial=1,i;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
factorial=factorial*i;
}
printf("%d!=%d\n",number,factorial);
}
C Programming ExamplesExplanation:
This C program calculates the factorial of a user-entered number. The factorial of a number is the product of all positive integers from 1 to that number. Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
Variable Declaration:
The following variables are declared:
- number (int): It is used to store the user’s input number for which the factorial will be calculated.
- factorial (int): It is used to store the result of the factorial calculation and is initialized to 1.
- i (int): A loop control variable to iterate from 1 to number.
User Input:
- The program prompts the user to enter a number with the message: “Enter a number for knowing its factorial”.
- The user’s input is read and stored in the number variable using scanf.
Factorial Calculation:
- The program enters a for loop that starts from i = 1 and continues until i is less than or equal to the number.
- Inside the loop, the value of factorial is updated by multiplying it by the current value of i. This operation calculates the factorial of the number.
Result Display:
- After the for loop, the program prints the calculated factorial with the message: “number! = factorial”.
End of Program:
- The program reaches the end of the main function and terminates.