1  import java.util.Scanner;
  2  
  3  /**
  4     This program combines several common loop algorithms. 
  5  */
  6  public class LoopAlgorithms
  7  {
  8     public static void main(String[] args) 
  9     {
 10        Scanner in = new Scanner(System.in);
 11  
 12        System.out.print("Enter input: ");
 13        int input = in.nextInt();
 14        int min = input; // The largest input
 15        int max = input; // The smallest input
 16  
 17        int count = 1; // The number of inputs
 18        int sum = input; // The sum of the inputs
 19  
 20        boolean foundNegative = false; // Set to true if we found at least one negative input
 21        int negatives; // The count of negative inputs
 22        int firstNegative = 0; // The position of the first negative input
 23  
 24        if (input < 0)
 25        {
 26           foundNegative = true;
 27           firstNegative = 1;
 28           negatives = 1;
 29        }
 30        else
 31        {
 32           negatives = 0;
 33        }
 34  
 35        boolean done = false;
 36        while (!done)
 37        {
 38           System.out.print("Enter input, 0 to quit: ");
 39           input = in.nextInt();
 40           if (input == 0) // Zero is the sentinel value
 41           {
 42              done = true;
 43           }
 44           else 
 45           {
 46              sum = sum + input; // Computing sum and average
 47              count++;
 48  
 49              if (input < min) // Determining minimum and maximum
 50              {
 51                 min = input;
 52              }
 53              else if (input > max)
 54              {
 55                 max = input;
 56              }
 57  
 58              if (input < 0) // Counting matches
 59              {
 60                 negatives++;
 61  
 62                 if (!foundNegative) // Finding first match
 63                 {
 64                    foundNegative = true;
 65                    firstNegative = count;
 66                 }
 67              }
 68           }
 69        }   
 70        System.out.println("Minimum: " + min);
 71        System.out.println("Maximum: " + max);
 72        System.out.println("Sum: " + sum);
 73        System.out.println("Average: " + sum * 1.0 / count);
 74        System.out.println("Negative values: " + negatives);
 75        if (foundNegative)
 76        {
 77           System.out.println("First negative: " + firstNegative);
 78        }
 79     }
 80  }