Java Online Compiler
Example: Maximum Handshakes Calculator (Iterative) in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Maximum Handshakes Calculator (Iterative) import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of people: "); int numberOfPeople = scanner.nextInt(); if (numberOfPeople < 0) { System.out.println("Number of people cannot be negative."); } else if (numberOfPeople <= 1) { // 0 or 1 person results in 0 handshakes System.out.println("Maximum number of handshakes: 0"); } else { long maxHandshakes = 0; // The first person shakes hands with (n-1) others. // The second person shakes hands with (n-2) new others (excluding the first). // ... and so on, until the last person has no new hands to shake. for (int i = 1; i < numberOfPeople; i++) { maxHandshakes += i; } System.out.println("Maximum number of handshakes: " + maxHandshakes); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS