Guest User

Untitled

a guest
Aug 15th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. /*
  2. Kurt Kaiser
  3. CTIM 168
  4. 08.02.2018
  5. Homework: Recursive Handshakes
  6. Chapter 11 Practice Problem 6
  7. */
  8.  
  9. public class RecursiveHandshake
  10. {
  11. // Use a recursive method to calculate the number of handshakes
  12. public static int handshake(int n)
  13. {
  14. // The base case: 0 or 1 handshakes for <=1 or 2 people
  15. if (n <= 1)
  16. return 0;
  17. else if (n == 2)
  18. return 1;
  19. // Each person shakes everyone's hand, subtract one keep going
  20. return (n-1) + handshake(n-1);
  21. }
  22.  
  23. // Main method to test the handshake method
  24. public static void main(String[] args)
  25. {
  26. int numberOfPeople = 10;
  27. int result = 0;
  28. for (int i = 0; i < numberOfPeople + 1; i++)
  29. {
  30. result = handshake(i);
  31. }
  32. System.out.println("Number of handshakes with " + numberOfPeople +
  33. " people: " + result);
  34. }
  35.  
  36. /*
  37. Solving without a recursive method is so much easier, haha
  38. public static int simpleHandshake(int n){
  39. if (n < 3){
  40. return (n-1);
  41. }
  42. int result;
  43. result = (n * (n-1))/2;
  44.  
  45. }
  46. */
  47. }
Add Comment
Please, Sign In to add comment