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?
- Accept n numbers.
- Convert the strings into integers using
Interger.parseInt()
function. - 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.
- Divide the sum by length.
- 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