While Loops

This loops finds the smallest, largest and the average.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Find total, count, print average 
package numbers;
import java.util.*;
public class Numbers {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); //do just once
    int count=0, total=0, num, small, large;
    System.out.print("Enter number:");;
    num=keyboard.nextInt();
    small=large=num; //first num is smallest & largest so far.
    while (num >=0) {
      total+=num;
      count++;
      if (num < small) small = num; // store new smallest
      if (num > large) large = num; // store new largest 
      System.out.print("Enter next number:");;
      num=keyboard.nextInt();
	}//while
    System.out.println("Total= "+total);
    System.out.println("Count="+count);
    if (count > 0) { // avoid dividing by zero! 
      System.out.println("Average= "+1.0*total/count);
      System.out.println("The numbers range from "+small+" to "+large);
    } //count>0
  }//main
}//class
CODE

Sample output:

Enter number:113
Enter next number:64
Enter next number:89
Enter next number:34
Enter next number:-1
Total= 300
Count=4
Average= 75.0
The numbers range from 34 to 113

To Do:

  • Run the program in your compiler. Try different sets of numbers.
  • Enter data that will cause the value of count to be 0.
  • Is the value that ends the loop included in the statistics?
  • What happens if the lowest or highest value appears twice?

NEXT: The do loop