Program to Calculate Factorial
Factorial of Given Number
We will write a C program to calculate the factorial of the given number and the number will be entered by the user. This will help to understand the basic structure of programming. In this program , we will calculate the factorial of given numbers easily by using proper syntax and algorithms.
Working of Program :
In the program, we will require some numbers from the user to calculate the factorial of that numbers.
Important Note:
- The factorial of zero will always be 1.
- The factorial of a negative number doesn’t exist.
Problem 1
Write a program to calculate the factorial of a given number.
- Firstly, we have to enter the number.
- Then print the factorial of the given number.
Code
#include<stdio.h> int main () { int n, fact; fact = 1; printf ("Enter the number = "); scanf ("%d", &n); while (n > 0) { fact = fact * n; n = n - 1; } printf ("The factorial = %d", fact); return 0; }
Output
Enter the number = 5 The factorial = 120
Note:
In the following we will find the factorial of the given number using do-while() loop.Syntax for do – while() loop:
do { // Statements // Increment / Decrement } while(condition)
Problem 2
Write a program to calculate the factorial of a given number using do-while() loop.
- Firstly, we have to enter the number.
- Then print the factorial of the given number.
Code
#include<stdio.h> int main () { int n, fact; fact = 1; printf ("Enter the number = "); scanf ("%d", &n); do { fact = fact * n; n = n - 1; } while (n > 0); printf ("The factorial = %d", fact); return 0; }
Output
Enter the number = 6 The factorial = 720
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment