Saturday, 10 January 2015

Java Program to find the average of all the elements in an array

This is a Java Program which finds  the average of all the elements in an array.

PROGRAM :
package codingcorner.in;

import java.util.Scanner;

public class AverageElementsArray {
 public static void main(String[] args) {
  int n, i;
  Scanner scan = new Scanner(System.in);
  float sum = 0, average;
  System.out.print("How many numbers ?\t");
  n = scan.nextInt();
  float numbers[] = new float[n];
  for (i = 0; i < n; i++) {
   System.out.print("Enter number " + (i + 1) + "\t");
   numbers[i] = scan.nextFloat();
  }
  scan.close();
  for (i = 0; i < n; i++)
   sum = sum + numbers[i];

  average = sum / n;
  System.out.print("\nThe average of " + n
    + "  numbers you entered is  :" + average);
 }
}

OUTPUT :
Java - Average of all the elements in an array

No comments:

Post a Comment