Opening Hours :7AM to 9PM
class SumArray { public int findSum(int[] arr) { int sum = 0; for (int i = 0; i < arr.length; i++) { sum += arr[i]; } return sum; } } public class Main { public static void main(String[] args) { SumArray sa=new SumArray(); int[] arr = {1, 5, 3, 8, 2, 9, 4}; int sum = sa.findSum(arr); System.out.println("The sum of all elements in the array is: " + sum); } }This program uses a for-loop to iterate through the array and add each element to a variable called sum. The sum is then returned as the result.
public class Main { public static void main(String[] args) { int[] arr = {1, 5, 3, 8, 2, 9, 4}; int sum = Arrays.stream(arr).sum(); System.out.println("The sum of all elements in the array is: " + sum); } }In both examples above, the output will be: