Solve the following problem recursively. Suppose that there are n people in a ro
ID: 3532355 • Letter: S
Question
Solve the following problem recursively.
Suppose that there are n people in a room where n >= 1. As each person initially entered the room they shook hands with all the people in the room once. Write a recursive method that returns the total number of handshakes that took place in a room with n people. For example, Handshake(1) must be 0. Handshake(2) will be 1. Handshake(3) will be 3 (when the third person entered the room they shook hands with the 2 people there already, as well there was a total of 1 handshake before that).
Explanation / Answer
// functions that takes persons(no. of persons) as int and returns no. of handshakes as int.
int Handshake(int persons){
if(persons==1){ // if persons equal to 1 ,it returns zero as no. of handshakes are 0.
return 0;
}
else{
return (persons-1)+Handshake(persons-1);
/*otherwise returns (persons-1) in addtion to the previous handshakes i.e.,Handshake(persons-1),. for e.g: returns Handshake(1)=0;Handshake(2)=1;Handshake(3)=3*/
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.