Java program to find average of all array elements

In this java program, we are going to read N integer elements and finding their average. By IncludeHelp Last updated : December 23, 2023

Problem statement

Given an array of integers and we have to find their average using java program.

Example

Input array elements: 65, 45, 25, 65, 84, 74, 96, 74, 15, 36
Output:
SUM of all elements: 579
Average of all elements: 57.9

Program to find average of all array elements in java

import java.util.*; 

public class FindAverage
{
	public static void main(String[] args) 
    {
		// declare and initialize here.
        int n,sum = 0;
        float average;
        
        // create object.
        Scanner s = new Scanner(System.in);
   
        // enter total number of elements you want.
        System.out.print("Enter number of elements you want in array : ");
        n = s.nextInt();
        int a[] = new int[n];
        
        // enter elements.
        System.out.println("Enter all the elements : ");
        for(int i = 0; i < n ; i++)
        {
            a[i] = s.nextInt();
            sum = sum + a[i];
        }

        // display sum of elements.
        System.out.print("Sum of the array elements is : " +sum+"\n");
        average = (float)sum / n;
        // display average of the elements.
        System.out.print("Average of the array elements is : " +average);
    }
}

Output

Enter number of elements you want in array : 10
Enter all the elements : 
65
45
25
65
84
74
96
74
15
36
Sum of the array elements is : 579
Average of the array elements is : 57.9

Java Array Programs »

More Java Array Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.