There are n people in a room, where n is an integer greater than or equal to 1.
ID: 3620626 • Letter: T
Question
There are n people in a room, where n is an integer greater than or equal to 1. Each person shakes hands once with every other person. What is the total number. h(n) of handshakes? Write a recursive function to solve this problem. To get you started, if there arc only one or two people in the room, then: handshake(l) = theta handshake(2) = 1 If a third person enters the room, she must shake hands with each of the two people already there. This is two handshakes in addition to the number of handshakes that would be made in a room of two people, or a total of three handshakes. if a fourth person enters the room, she must shake hands with each of the three people already present. This is three handshakes in addition to the number of handshakes that would be made in a room of three people, or six handshakes. If you can generalize this to n handshakes then it should help you write the recursive solution.Explanation / Answer
please rate - thanks import java.util.*;class recursivehandshakes
{public static void main(String[] args)
{int num;
Scanner in=new Scanner(System.in);
System.out.print("Enter the number of people in the room number: ");
num=in.nextInt();
while(num<1)
{System.out.println("Must be at least 1 person in the room");
System.out.print("Enter the number of people in the room number: ");
num=in.nextInt();
}
System.out.println("There will be "+hands(num)+" handshakes");
}
public static int hands(int n)
{if(n<3)
return n-1;
else
return (n-1+hands(n-1));
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.