C++ Program to find the maximum number of handshakes

Program to find the maximum number of handshakes

Here we will discuss how to find the maximum number of handshakes which can happen between N number of people given the fact that any two people shake hands exactly once using C++ programming language.

For the number of handshakes to be maximum, every person should shakehand with every other person in the room i.e all persons present should shake hands. For the first person, there would be N-1 people to shake hands. For second person there would N-1 people available but as he had already shaken hands with the first person,  there would be N-2 people to shake hands and so on.

Therefore the total number of handshake = (N-1 + N-2 +….+ 1 + 0),

which is equivalent to ((N-1)*N)/2.

program to find maximum number of handshakes

Working

Let’s see how the code works:

  • User gives an input(number of people).
  • The input is stored in an int type variable say p.
  • By using the formula the maximum number of handshakes between p people are found and stored in another variable say max.

            int max=p*(p-1)/2;

  • max is printed as output.

C++ Code

//C++ Program
//Maximum number of handshakes
#include<iostream>
using namespace std;
//main program
int main()
{
int p;
cout<<"Enter number of Persons: ";
//user input
cin>>p;
cout<<"Maximum number of handshakes: ";
//find maximum number of handshakes using formula
int max=p*(p-1)/2;
//printing output
cout<<max;
return 0;
}

Output

Enter number of Persons: 15
Maximum number of handshakes: 105

Please Login/Signup to comment