Saturday 20 August 2016

Chapter 7 Exercise 8, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

7.8 (Average an array) Write two overloaded methods that return the average of an array with the following headers:
public static int average(int[] array)
public static double average(double[] array)

Write a test program that prompts the user to enter ten double values, invokes this method, and displays the average value. 



import java.util.Scanner;
 
public class ProgrammingEx7_8 {
 
 public static void main(String[] args) {
  System.out.print("Enter the 10 floating point numbers:");
  Scanner input = new Scanner(System.in);
  double[] numbers = new double[10];
 
  for (int i = 0; i < numbers.length; i++) {
   numbers[i] = input.nextDouble();
  }
 
  System.out.println("The average is " + average(numbers));
 
 }
 
 public static int average(int[] array) {
  int sum = 0;
  for (int i = 0; i < array.length; i++) {
   sum += array[i];
  }
 
  return sum / array.length;
 
 }
 
 public static double average(double[] array) {
  double sum = 0;
  for (int i = 0; i < array.length; i++) {
   sum += array[i];
  }
 
  return sum / array.length;
 }
 
}

1 comment :

  1. good work, I like to use the new for each loops when I can, maybe show a few examples with these

    ReplyDelete