Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to calculate the sum of all elemets of an array .

Java Code Example — Array Programs

ADVERTISEMENT

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

  1. Create a class with a method sum(int[] ar) that accepts an integer array.
  2. Initialize a variable sum to 0.
  3. Use a for loop starting from i = 0 to ar.length - 1.
  4. In each iteration, add the current array element ar[i] to sum.
  5. After the loop, print the total sum.
  6. 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 length gives 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.
ADVERTISEMENT