Java Program to calculate the sum of all elemets of an array .
Objective
Write a Java program to calculate the sum of all elements in an integer array.
Algorithm / Approach
- Create a class with a method
sum(int[] ar)that accepts an integer array. - Initialize a variable
sumto 0. - Use a
forloop starting fromi = 0toar.length - 1. - In each iteration, add the current array element
ar[i]tosum. - After the loop, print the total
sum. - In
main, initialize an array with hardcoded values and pass it to the method.
Test.java
class Test {
void sum(int[] ar) {
int sum = 0;
for(int i = 0; i< ar.length; i++) {
sum = sum + ar[i];
}
System.out.print("Sum = "+sum);
}
public static void main(String[] a)
{
int[] arr = {7,2,5,4,5};
Test t = new Test();
t.sum(arr);
}
}
Expected Output
Sum = 23
Explanation of the Program
- An array is a data structure that stores a fixed-size sequential collection of elements of the same type.
- To access elements in an array, we use a zero-based index. The property
lengthgives the total number of elements. - This program iterates through every index, taking the value stored there and accumulating it into a running total variable.
Complexity
Time Complexity
O(n) - Where n is the number of elements in the array.
Space Complexity
O(1) - The array is passed by reference, no extra space is used.