C Program to calculate nPr (Permutation) and nCr (Combination) using loop
1.) nPr (Permutation):-
Permutation is used to calculate the number of ways to arrange r objects selected from n objects, where order is important.
Formula
nPr = n! / (n − r)!
C Program
#include <stdio.h>int main(){long int n, r, i;long int factn = 1, factnr = 1;long int npr;printf("Enter positive integer value of n: ");scanf("%ld", &n);printf("Enter positive integer value of r: ");scanf("%ld", &r);if (n >= r && r >= 0){for (i = 1; i <= n; i++)factn = factn * i;for (i = 1; i <= n - r; i++)factnr = factnr * i;npr = factn / factnr;printf("nPr value = %ld", npr);}else{printf("Invalid input! Ensure n >= r >= 0.");}return 0;}
Sample Output
Enter positive integer value of n: 5Enter positive integer value of r: 2nPr value = 20
Explanation (English)
The program calculates the factorial of n and n-r using for loops. It then applies the permutation formula to calculate nPr.
व्याख्या (हिन्दी)
यह प्रोग्राम for लूप की सहायता से n तथा n-r के फैक्टोरियल की गणना करता है। इसके बाद Permutation के सूत्र का उपयोग करके nPr का मान निकालता है।
Example
If 5 objects are available and 2 objects are arranged, there are 20 possible permutations because order matters.
यदि 5 वस्तुओं में से 2 वस्तुओं को क्रम में व्यवस्थित किया जाता है, तो कुल 20 Permutation बनते हैं, क्योंकि यहाँ क्रम महत्वपूर्ण होता है।
2.) nCr (Combination):-
Combination is used to calculate the number of ways to select r objects from n objects without considering their order.
Formula
nCr = n! / (r! × (n − r)!)
C Program
#include <stdio.h>int main(){long int n, r, i;long int factn = 1, factr = 1, factnr = 1;long int ncr;printf("Enter positive integer value of n: ");scanf("%ld", &n);printf("Enter positive integer value of r: ");scanf("%ld", &r);if (n >= r && r >= 0){for (i = 1; i <= n; i++)factn = factn * i;for (i = 1; i <= r; i++)factr = factr * i;for (i = 1; i <= n - r; i++)factnr = factnr * i;ncr = factn / (factr * factnr);printf("nCr value = %ld", ncr);}else{printf("Invalid input! Ensure n >= r >= 0.");}return 0;}
Sample Output
Enter positive integer value of n: 5Enter positive integer value of r: 2nCr value = 10
Explanation (English)
The program calculates the factorials of n, r, and n-r using for loops. It then applies the combination formula to calculate nCr.
व्याख्या (हिन्दी)
यह प्रोग्राम for लूप की सहायता से n, r तथा n-r के फैक्टोरियल की गणना करता है। इसके बाद Combination के सूत्र का उपयोग करके nCr का मान निकालता है।
Example
If 5 objects are available and 2 objects are selected, there are 10 possible combinations.
यदि 5 वस्तुओं में से 2 वस्तुओं का चयन किया जाता है, तो कुल 10 Combination बनते हैं।
Comments
Post a Comment