Sum And Average Of Values In An Array In Java

Hello guys!! Welcome to flower brackets. In this post we going to learn how to calculate sum and average of values in an array in java.

Okay, in this program we will use an array and loop to calculate the sum and average of a set of values in java.

So let’s start by declaring the array

example: Sum And Average Of Values In An Array In Java

public class SumAverageDemo
{
public static void main(String[] args)
{
double var[] = {2,4,6,8,10};
double sum = 0;
for(double value : var)
{
sum += value;
}
System.out.println("The sum is : " + sum);
double average = 0;
if(var.length > 0)
{
average = sum / var.length;
}
System.out.println("The average is : " + average);
}
}

Output:

Sum And Average Of Values In An Array In Java


maximum and minimum values in an array in java

Right, this program will show you how to calculate the maximum and minimum values inside of an array.

Also Read – Calculate Average Of An Array In Java

So I just have array here,

Maximum:

public class SumAverageDemo
{
public static void main(String[] args)
{
double var[] = {21,40,61,85,100};
double max = var[0];
for(int a = 0;a < var.length;a++)
{
if(var[a] > max)
{
max = var[a];
}
}
System.out.println("The maximum number is : " + max);
}
}

Output:

The maximum number is : 100.0

Minimum:

public class SumAverageDemo
{
public static void main(String[] args)
{
double var[] = {21,40,61,85,100};
double min = var[0];
for(int a = 0;a < var.length;a++)
{
if(var[a] < min)
{
min = var[a];
}
}
System.out.println("The minimum number is : " + min);
}
}

Output:

The minimum number is : 21.0

conclusion:

So this is all about how to calculate sum and average of values in an array. We also learnt how to calculate maximum and minimum values in an array.

I hope you had fun and have understood above concept. Subscribe to my blog flower brackets if you haven’t.

If you find this post useful share it across social media.

About the author

admin

View all posts

Leave a Reply

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