Java Program to Calculate Sum and Average of an Array

Java program to calculate sum & average of an array. calculate the sum and average of an array in Java. Enter the array’s size, followed by all of the array’s elements. Now, using the for loop, we calculate the sum of the array’s elements and divide it by the number of items in the array to get the average. the Java source code for calculating the sum and average of an array

import java.util.Scanner;
public class Main
public static void main(String[] args)
int n, sum = 0;
float average;
Scanner s = new Scanner(;
System.out.print("Enter number of elements you want in array");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements");
for(int i = 0; i < n ; i++)
a[i] = s.nextInt();
sum = sum + a[i];
average = (int)sum / n;



Enter number of elements you want in array 5
Enter all the elements

nextInt in Java Program

The java.util. Scanner class’s nextInt method scans the next token of the input as an Int. If the translation is successful, the scanner moves past the matched input. If the parameter radix is not passed, it behaves similarly to nextInt, with the radix assumed to be the default.

For Loop to Execute Java program to Calculate Sum & Average of an Array

The “for” loop in Java is an entry-controlled loop that allows a user to iteratively execute a block of statement for a fixed number of times. The number of iterations is determined by the test condition specified within the “for” loop. The Java “for” loop is one of the simplest Java loops to grasp. 

A “For” Loop is used to iterate over a specific block of code a predetermined number of times. A for-loop or simply for loop is a control flow statement in computer science that specifies iteration and allows code to be executed repeatedly.