Average of N Numbers in Java

Average of N Numbers in Java

Problem:

Write a java program to find average of n numbers.

How to find average of N Numbers in java?

  1. Accept n numbers.
  2. Convert the strings into integers using Interger.parseInt() function.
  3. Sum up the numbers starting from index 0 to value of length N because each array has a length attribute which stores the length of array.
  4. Divide the sum by length.
  5. Print the average of n numbers

Java program to find average of n numbers

/* Aim: Write a java program to accept n integers and find the average */

import java.io.*;

public class Main {
    public static void main(String args[]) throws IOException {
    
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    int sum = 0;
    
    
	System.out.print("How many integers to accept: ");
    
    int n = Integer.parseInt(br.readLine()); 
    
    for(int i=0;i<n;i++)
    {
    	int counter = i + 1;
    	System.out.print("Enter " + "number" + " " + counter + ": ");
        sum +=Integer.parseInt(br.readLine());
    }

    int average = sum / n;
    
    System.out.println("Average of " + n + " numbers is " + average);
    }
}

Note: Save the program with Main.java as filename to avoid error.

Output of Java program:

How many integers to accept: 3
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Average of 3 numbers is 20

Comments