Sum and average of array elements in java [2 ways].
Hey in this article you can learn how to find the sum and average of array elements in java with 2 different approaches. i.e
Requirements
- Find the sum and average of array elements
Input :- 1,3,5,2,0
Output:-
Sum = 11
Average = 2
Approach:-1 "find sum and average of array elements using for loop"
public class byForLoop
{
public static void main(String[] args)
{
int[] arr = {4,6,9,2,0,4};
int len = arr.length;
System.out.println("Length of array is: "+len);
//Sum
int sum = 0;
for(int i = 0; i < len; i++)
{
sum = sum + arr[i];
}
System.out.println("The sum is: "+sum);
float avg = sum / len;
System.out.println("The average is: "+avg);
}
}
Length of array is: 6
The sum is: 25
The average is: 4.0
➜ We can find the total sum of Array elements by adding each elements one by one. We can do that by using loop.
➜ Using loop we can able to access array elements individually.
➜ Now we can add elements to a sum variable one by one.
➜ To find the average we have to divide the total sum with length of the array.
➜ I have previously determined the length of array to len variable. Now using division operator we can find the average.
Download .java file Here
You can download the .java file for the program 'find sum and average of array elements using for loop'
Download .pdf file (Code with Notes)
You can download all the programs with explanation notes with pdf format.'
Approach:-2 "determine the sum and average of array elements using for each loop"
public class forEachLoop
{
public static void main(String[] args)
{
System.out.println("======By for each loop=====");
int[] arr = {4,6,9,2,0,4};
int len = arr.length;
System.out.println("Length of array is: "+len);
//Sum
int sum = 0;
for(int num : arr)
{
sum = sum + num;
}
System.out.println("The sum is: "+sum);
float avg = sum / len;
System.out.println("The average is: "+avg);
}
}
======By for each loop=====
Length of array is: 6
The sum is: 25
The average is: 4.0
Using for-each loop also we can achieve out requirements.
Download .java file Here
You can download the .java file for the program 'find sum and average of array elements using for each loop'
Download .pdf file (Code with Notes)
You can download all the programs with explanation notes with pdf format.'
If you get any doubt, feel free to write it on the comment below, I will definitely answer to your questions.
And Yes if you think it is informative, please share it with your friends.