Array Sum Calculation

This program calculates the sum of elements in an array.

Problem Statement

Write a Java program to calculate the sum of all elements in an integer array.

Source Code

1 public class ArraySum {
2 public static void main(String[] args) {
3 int[] arr = {5, 10, 15, 20, 25};
4 int sum = 0;
5 for(int i=0; i<arr.length; i++) {
6 sum += arr[i];
7 }
8 System.out.println("Sum of array elements: " + sum);
9 }
10 }

Program Output

Sum of array elements: 75

Explanation

The variable sum is initialized to 0 and the for loop iterates through each element of the array adding it to sum, so the final result prints the total sum, demonstrating an aggregation operation on arrays.

Quick Links to Explore