Calculate the Sum of Elements in an Array
Understanding Sum Calculation
Summing elements in an array involves adding all the elements together to get a total sum.
We will explore three different methods to calculate the sum of an array using Java.
Method 1: Using a Loop
This method iterates through the array and accumulates the sum.
public class SumArrayLoop { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int sum = 0; for(int num : arr) { sum += num; } System.out.println("Sum: " + sum); } }
Method 2: Using Recursion
This method calculates the sum recursively.
public class SumArrayRecursion { public static int sumRecursive(int[] arr, int n) { if (n == 0) return 0; return arr[n - 1] + sumRecursive(arr, n - 1); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; System.out.println("Sum: " + sumRecursive(arr, arr.length)); } }
Method 3: Using Streams
This method calculates the sum using Java Streams.
import java.util.Arrays; public class SumArrayStream { public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5}; int sum = Arrays.stream(arr).sum(); System.out.println("Sum: " + sum); } }