C Program to Calculate Factorial of a Number Using Recursion
A recursive function is a function that calls itself to solve a problem. In this program, we use a recursive function named factorial() to calculate the factorial of a given positive integer.
रिकर्सिव फंक्शन वह फंक्शन होता है जो किसी समस्या को हल करने के लिए स्वयं को कॉल करता है। इस प्रोग्राम में हम दी गई धनात्मक पूर्णांक संख्या का फैक्टोरियल निकालने के लिए factorial() नामक रिकर्सिव फंक्शन का उपयोग करेंगे।
Formula:
n! = n × (n-1) × (n-2) × ... × 10! = 1
C Program
#include <stdio.h>unsigned long long factorial(unsigned int n){if (n == 0)return 1;return n * factorial(n - 1);}int main(void){long long n;printf("Enter a positive integer (0 to 20): ");if (scanf("%lld", &n) != 1 || n < 0 || n > 20){printf("Invalid input! Please enter a number from 0 to 20.\n");return 1;}printf("Factorial of %lld = %llu\n", n, factorial((unsigned int)n));return 0;}
Output 1
Enter a positive integer (0 to 20): 5Factorial of 5 = 120
Output 2
Enter a positive integer (0 to 20): 0Factorial of 0 = 1
Explanation
The
factorial()function takes an unsigned integer as an argument and returns anunsigned long longvalue.The condition
if (n == 0)is the terminating condition or base case. It returns 1 because the factorial of zero is 1.The statement
return n * factorial(n - 1);calls the same function recursively with a smaller value.When the base case is reached, the pending multiplication operations are completed while the recursive calls return their results.
The program accepts values from 0 to 20 because the factorial of 20 is the largest factorial that fits in the standard minimum range of
unsigned long long.factorial()फंक्शन आर्गुमेंट के रूप में एक unsigned integer लेता है तथाunsigned long longवैल्यू वापस करता है।if (n == 0)टर्मिनेटिंग कंडीशन या बेस केस है। यह 1 वापस करता है क्योंकि शून्य का फैक्टोरियल 1 होता है।return n * factorial(n - 1);स्टेटमेंट उसी फंक्शन को छोटी संख्या के साथ रिकर्सिव रूप से कॉल करता है।जब बेस केस प्राप्त हो जाता है, तब रिकर्सिव कॉल वापस आते समय पहले से लंबित गुणा की क्रियाएँ पूरी करती हैं।
प्रोग्राम में 0 से 20 तक की संख्याएँ स्वीकार की गई हैं क्योंकि 20 का फैक्टोरियल
unsigned long longकी मानक न्यूनतम क्षमता में आने वाला सबसे बड़ा फैक्टोरियल है।
Note: The factorial of a negative integer is not defined in the ordinary factorial definition used in this program. Also, factorial values grow very quickly, so using an appropriate data type and checking the input range is important.
नोट: इस प्रोग्राम में उपयोग की गई सामान्य फैक्टोरियल परिभाषा के अनुसार ऋणात्मक पूर्णांक का फैक्टोरियल परिभाषित नहीं होता। इसके अतिरिक्त, फैक्टोरियल का मान बहुत तेजी से बढ़ता है, इसलिए उचित डेटा टाइप तथा इनपुट रेंज का ध्यान रखना आवश्यक है।
Comments
Post a Comment