java

Calculate the average using array in Java

In this tutorial, we are going to see two programs for calculating the average using array in Java. The first program finds the average of the elements in the specified array. The second program takes the value of n (number of elements) and the numbers provided by the user and try to find the average of these numbers using an array.
 

Example 1: Program to calculate the average using an array
public class Main {

    public static void main(String[] args) {
        double[] marks = {15, 8.99, 16, 18, 13.2, 10};
        double total = 0;

        for(int i=0; i < marks.length; i++){
        	total = total + marks[i];
        }

        double avg = total / marks.length;
		
        System.out.format("The average is: %.2f", avg);
    }
}

 
Output:

The average is: 13.53

 

 

Example 2: Calculate the average of the numbers entered by the user
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
		
        System.out.print("Enter the number of students : ");
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        double[] marks = new double[n];
        double total = 0;

        for(int i=0; i < marks.length; i++){
        	System.out.print("Enter the ("+(i+1)+") student's mark :");
        	marks[i] = sc.nextDouble();
        }
        sc.close();
        for(int i=0; i < marks.length; i++){
        	total = total + marks[i];
        }

        double avg = total / marks.length;
        
        System.out.format("The class average is: %.2f", avg);
    }
}

 
Output:

Enter the number of students : 3
Enter the (1) student's mark: 10
Enter the (2) student's mark: 15.89
Enter the (3) student's mark: 12.23
The class average is: 12.71
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *