Write a Java program to find the sum of elements in an array.
The provided Java program calculates the sum of the elements in an array.
class Main {
public static void main(String[] args) {
int[] arr = {6, 6, 7, 8, 8, 9};
int sum = sumOfArr(arr);
System.out.println("Sum of elements in the array: " + sum);
}
public static int sumOfArr(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}
}
Output:
Sum of elements in the array: 44
How It Works
- Input Array:
- The input array is {6, 6, 7, 8, 8, 9}.
- sumOfArr Method:
- The sumOfArr method loops through each element of the array using an enhanced for loop.
- It adds each number in the array to the sum variable.
- Returning the Sum:
- After looping through all the elements, the total sum is returned to the main method.
- Output:
- The sum of the array elements is printed.
Execution:
- Initialize sum = 0.
- Loop through the array:
- Add 6 to sum → sum = 6
- Add 6 to sum → sum = 12
- Add 7 to sum → sum = 19
- Add 8 to sum → sum = 27
- Add 8 to sum → sum = 35
- Add 9 to sum → sum = 44
- Return sum = 44.
Advantages
- Simple and Efficient:
- The code uses a basic loop to iterate over the array and calculate the sum, which is efficient for arrays of reasonable size.
- Readability:
- The method is clear and easy to understand, making it straightforward for other developers to follow.
Edge Cases
- Empty Array:
- Input: arr = {}
- Output: Sum of elements in the array: 0
- Array with Negative Numbers:
- Input: arr = {-1, 5, -3, 2}
- Output: Sum of elements in the array: 3
- All Zeroes:
- Input: arr = {0, 0, 0, 0}
- Output: Sum of elements in the array: 0