Search code examples
c++permutation

Permutation calculator isn't working in C++


Good day! I am having some trouble with my permutation calculator. For some reason, the end result is always 1. We are not allowed to use recursion at the moment so I opted to use a for loop for finding the factorials.

Here is my code:

#include <iostream>
using namespace std;

int fact(int x);
int perm(int y, int z);
int n, r, npr;
char ch;


int main()
{

    do{

        cout<<"Enter n (object/s): ";
        cin>> n;
        cout<< "Enter r (sample/s): ";
        cin>> r;


        npr= perm(n,r);

        cout<< "Value of "<< n<<"P"<< r<< " = "<< npr<<endl;
        cout<<"Would you like to repeat this again? [y/n] \n";
        cin>> ch;
        cout<< "\n";

    } while(ch=='y');

    cout<< "Thank you and have a nice day!";

    return 0;
}


int fact(int x)
{
   int number, cum = 1;

    for(number=1;number<=n;number++)
      cum=cum*number;

    return cum;
}

int perm(int y, int z)
{

    return fact(n) / fact(n-r);
}


Solution

  • The problem in your code is unecessary abuse of global variables. This function:

    int fact(int x) 
    {
       int number, cum = 1;
    
        for(number=1;number<=n;number++)
          cum=cum*number;
    
        return cum;
    }
    

    Always calculates the factorial of n. No matter what parameter you pass when calling it, hence here:

    int perm(int y, int z)
    {
    
        return fact(n) / fact(n-r);
    }
    

    fact(n) returns the factorial of n. fact(n-r) returns the factorial of n. And the result is always 1. Remove the globals and make the functions acutally use their arguments:

    #include <iostream>
    
    int fact(int x);
    int perm(int y, int z);
    
    
    int main() {
    
        int n = 0;
        int r = 0;
        char ch = 'n';
    
        do{    
            std::cout << "Enter n (object/s): \n";
            std::cin >> n;
            std::cout << "Enter r (sample/s): \n";
            std::cin >> r;
            auto npr = perm(n,r);
            std::cout << "Value of "<< n << "P" << r << " = " << npr << "\n";
            std::cout << "Would you like to repeat this again? [y/n] \n";
            std::cin >> ch;
            std::cout << "\n";  
        } while(ch=='y');
    
        std::cout << "Thank you and have a nice day!";
    }
    
    int fact(int x) {
       int cum = 1;   
       for(int number=1;number<=x;number++) {
          cum=cum*number;
       }
       return cum;
    }
    
    int perm(int y, int z) {
        return fact(y) / fact(y-z);
    }