Java Program to Find Sum and Average of All Elements in an Array
In this post, you will learn how to find the sum and average of all elements in an array using the Java programming language.
Algorithm
- Start
- Initialize
sum = 0
n = size of the array - Input the elements of the array.
- For each element i in the array (from index 0 to n-1)
- Add the element to sum.
- sum = sum + array[i]
- Calculate the average: average = sum / n
- Output the sum and average.
- End
import java.util.Scanner;
public class SumAndAverage {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Size of the array
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
// Input: Elements of the array
int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
// Calculate sum of elements
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
// Calculate average of elements
double average = (double) sum / n;
// Output the results
System.out.println("Sum of all elements: " + sum);
System.out.println("Average of all elements: " + average);
scanner.close();
}
}
Output of the above code:
Enter the number of elements in the array: 5
Enter the elements of the array:
10
20
30
40
50
Sum of all elements: 150
Average of all elements: 30.0
Explanation:
Step 1: We start by initializing the sum to 0 and determining the size of the array n.
Step 2: The elements of the array are read from the user or input source.
Step 3: We iterate through each element in the array, adding its value to the sum.
Step 4: After computing the total sum, we calculate the average by dividing the sum by the total number of elements n.
Step 5: Finally, we output the calculated sum and average.
Related Articles
Number pattern programs in JavaJava program to find area of rectangle
Matrix multiplication in Java
Electricity bill program in Java
Java program to find area of triangle
Area of circle program in Java
Remove duplicate elements from array in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Convert decimal to hexadecimal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number