In this tutorial, we will write a java program to calculate the sum of all the elements present in an array. Although it is quite simple, you still need to have an idea of the proper function of following in java:
The for loop in the program runs starting from 0 (array index starts from 0) to the total length of an array (i.e. till the last index). An inbuilt function is used to find the length of an array (array.length
).
Java Program to Find the Sum of all the Elements in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //find the sum of an array in java public class SumOfAnArray { public static void main(String[] args) { int sum = 0; //Initializing array int [] arr = new int [] {5, 4, 6, 1, 9}; //sum of array for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println("Sum of all the elements of an array: " + sum); } } |
Output:
Sum of all the elements of an array: 25