C Exercises: Calculate the factorial of a given number
C For Loop: Exercise-15 with Solution
Write a C program to calculate the factorial of a given number.
Visual Presentation:
Sample Solution:
C Code:
#include <stdio.h> // Include the standard input/output header file.
int main(){
int i, f = 1, num; // Declare variables 'i' for loop counter, 'f' to store factorial, 'num' for user input.
printf("Input the number : "); // Print a message to prompt user input.
scanf("%d", &num); // Read the value of 'num' from the user.
for(i = 1; i <= num; i++) // Start a loop to calculate factorial.
f = f * i; // Calculate factorial.
printf("The Factorial of %d is: %d\n", num, f); // Print the calculated factorial.
return 0; // Indicate that the program has executed successfully.
}
Sample Output:
Input the number : 5 The Factorial of 5 is: 120
Explanation:
for (i = 1; i <= num; i++) f = f * i;
In the above for loop, the variable i is initialized to 1, and the loop will continue as long as i is less than or equal to the value of variable 'num'. In each iteration of the loop, the value of variable 'f' is updated by multiplying it with the value of i using the assignment operator (*=).
The loop will increment the value of i by 1, and the process will repeat until the condition i<=num is no longer true.
Flowchart:
C Programming Code Editor:
Previous: Write a program in C to make such a pattern like a pyramid with an asterisk.
Next: Write a program in C to display the n terms of even natural number and their sum.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics