C++ Program to find Permutations in which n people can occupy r seats in a classroom

Program to find Permutations in which n people can occupy r seats in a classroom

Here we will discuss how to find the number of ways N people can occupy R seats in a classroom in C++ programming language.

This is a problem specific program which deals with problems like in how many ways employees can be arranged in the seats available in a company or the same for the students in a school or college.

This problem can be easily solved by the use of the simple formula of permutations which is

nPr =    n! / (n-r)!

Example: we have 5 students and the total number of seats are 6.

Permutations             =    6P5

=    6! / (6-5)!

=    720.

So, there are 720 ways in which 5 students can be arranged in 6 seats.

Program to find permutations

Working

Let’s see how the code works:

  • User gives two inputs(number of people and seats).
  • The inputs are stored in two int type variables say n(number of people) & r(number of seats).
  • If the number is people are more than the number of seats then stop the program otherwise go to next step

        if(r<n)

                 cout<<“Cannot adjust “<<n<<” people on “<<r<<” seats”;

                 return 0;

  • Find all the possible arrangements using the formula of permutation

        int p=fact(r)/fact(r-n);

  • Print the output. 

C++ Code

//C++ Program
//Permutations in which n people can occupy r seats
#include<iostream>
using namespace std;
//function for factorial
int factorial(int num)
{
int fact=1;
for(int i=num;i>=1;i--)
fact*=i;
return fact;
}
//main program
int main()
{
int n,r;
cout<<"Enter number of people: ";
//user input
cin>>n;
cout<<"Enter number of seats: ";
//user input
cin>>r;
//if there are more people than seats
if(r<n)
{
cout<<"Cannot adjust "<<n<<" people on "<<r<<" seats";
return 0;
}
//finding all possible arrangements of n people on r seats
// by using formula of permutation
int p = factorial(r)/factorial(r-n);
//printing output
cout<<"Total arrangements: "<<p;
return 0;
}

Output

Enter number of people: 5
Enter number of seats: 6
Total arrangements: 720

Please Login/Signup to comment