C Program to Calculate Factorial of a Number Using Function फंक्शन का उपयोग करके किसी संख्या का Factorial ज्ञात करने का C प्रोग्राम
In C language, a user-defined function can be used to calculate the factorial of a number. The factorial of a non-negative integer is the product of all positive integers from 1 to that number.
C भाषा में User-Defined Function का उपयोग करके किसी संख्या का Factorial ज्ञात किया जा सकता है। किसी non-negative integer का factorial, 1 से उस संख्या तक की सभी धनात्मक पूर्ण संख्याओं का गुणनफल होता है।
Formula (सूत्र)
n! = n * (n-1) ...*3*2*1
Example:
5! = 5 * 4 * 3 * 2 * 1 = 120
Also, (0! = 1).
C Program
#include <stdio.h>unsigned long long factorial(int x);int main(void){int n;unsigned long long ans;printf("Enter an integer number: ");scanf("%d", &n);if (n >= 0 && n <= 20){ans = factorial(n);printf("Factorial of %d = %llu\n", n, ans);}else{printf("Invalid input! Enter a number from 0 to 20.\n");}return 0;}unsigned long long factorial(int x){int i;unsigned long long fact = 1;for (i = 1; i <= x; i++){fact = fact * i;}return fact;}
Output
Example 1:
Enter an integer number: 5Factorial of 5 = 120
Example 2:
Enter an integer number: 0Factorial of 0 = 1
Explanation (व्याख्या)
The
factorial()function is declared before themain()function.factorial()function कोmain()function से पहले declare किया गया है।The user enters an integer number.
यूजर एक integer number इनपुट करता है।
The
ifcondition checks whether the number is between 0 and 20.ifcondition जाँचती है कि संख्या 0 से 20 के बीच है या नहीं।The
factorial()function calculates the factorial using aforloop.factorial()functionforloop की सहायता से factorial की गणना करता है।The calculated factorial is returned to the
main()function and displayed.Calculate किया गया factorial
main()function को return किया जाता है और प्रदर्शित किया जाता है।
Important Points
Factorial is defined only for non-negative integers.
The factorial of 0 is always 1.
factorial()is a user-defined function.The return type
unsigned long longsupports factorial values up to 20! on commonly used C implementations.Factorial grows very quickly, so larger values may cause integer overflow.
Comments
Post a Comment