Solve the following problem recursively. Suppose that there are n people in a ro
ID: 3532363 • 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
public static int HandShake(int n){//n people
if(n==1) //Handshake(1) must be 0
return 0;
else
return (n-1)+HandShake(n-1);// there will be n-1 handshakes for n person entering
//and call HandShake(n-1) to return the handshakes that took place before n 'person enter room'
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.