Find NCR and NPR in C++ Console

This C++ program shows you how to calculate the NCR and NPR of two given numbers. NCR is basically a combination number i.e. if you had N number of distinct objects then taking R objects at a time, NCR determines how many combinations are possible. In NPR, we get the number of permutations i.e. the combinations but with the sequence being also taken into account. 
Basically in NCR, AB is a single combination. But in NPR, AB and BA are two different permutations of a combination of A and B. The difference is quite clear and is easy for us to note that permutations are always equal to of greater in most cases than the combinations of elements. Also note that any number raised to the power of zero is one. This is a situation encountered during calculation of NCR and NPR.

Have a look at the code below followed by the source code:


#include <iostream>

using namespace std;

// These three lines deal with the function declarations. It is very
// important to declare functions before defining them.
// When declaring, just use the datatype in the parameter not
// followed by any variable. 

long NCR_Function(int , int );
long NPR_Function(int , int );
long factorial(int);

int main()
{
    int n, r;
    long ncr, npr;

    cout<<"Enter the value of n and r\n";
    cin>>n>>r;

    ncr = NCR_Function(n, r);
    npr = NPR_Function(n, r);

    cout<<"\nNCR: ";
    cout<<n<<"  and   "<<r<<"   is  "<<ncr<<"\n";

    cout<<"\nNPR: ";
    cout<<n<<"  and   "<<r<<"   is  "<<npr<<"\n";

    cin>>n;

    return 0;
}

// The function below calculates the NCR value. 

long NCR_Function(int n, int r)
{
    long result;

    result = factorial(n)/(factorial(r)*factorial(n-r));

    return result;
}

// The function below calculates the NPR value. 

long NPR_Function(int n, int r)
{
    long result;

    result = factorial(n)/factorial(n-r);

    return result;
}

// The function below is used to calculate the factorial of a given 
// number. This is used in both NCR and NPR. 

long factorial(int n)
{
    int c;
    long result = 1;

    for( c = 1 ; c <= n ; c++ )
        result = result*c;

    return ( result );
}


Download Source Code Here. Notice that the C++ Souce Code is written in Code::Blocks 12.11 IDE available for direct download Here.

Please ask your questions and list your suggestions below in the comments section.

No comments:

Post a Comment

Custom Search