Java Program To Find the Sum of an Array

In this article, you will learn how to find the sum of an Array in java. Here we used an integer array and for loop to calculate the sum of a given array.

Algorithm:

  1. Initialize an array arr and a variable sum.
  2. Initialize the value of sum=0.
  3. Start a for loop from index 0 to the length of the array – 1.
  4. In each iteration, perform sum = sum + arr[i].
  5. After the completion of the loop, print the value of the sum.

Let’s see a few examples below:

Example #1. Calculate the sum of an Array

In this example, we declare and initialize an integer array with some values. After that iterate, the array using for loop and add each element of the array to find the total sum. Let’s see the java program below:

package com.javacodepoint.array;

public class SumOfArray {

	public static void main(String[] args) {

		// Declare and Initialize an integer Array
		int arr[] = { 4, 5, 1, 6, 4, 15, 7 };

		// Declare a sum variable to calculate the sum of the array.
		int sum = 0;

		// Iterating all array element to calculate the sum
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}

		// Printing the calculated total sum
		System.out.println("The total sum of the given array: " + sum);

	}

}

OUTPUT:

The total sum of the given array: 42

Example #2. Calculate the sum of the array for users given value

In this example, we will ask the user to decide the size of the array and provides its element value. To take inputs from users, we used java.lang.Scanner class here. Let’s see the java program below:

package com.javacodepoint.array;

import java.util.Scanner;

public class SumOfArray2 {

	public static void main(String[] args) {

		// Creating scanner object for reading user inputs
		Scanner sc = new Scanner(System.in);

		// Read the size of the Array
		System.out.println("Enter the size of the Array: ");
		int n = sc.nextInt();

		// Declare the integer Array of given size
		int arr[] = new int[n];

		// Reading the Array values
		System.out.println("Enter " + n + " element(s) of the Array: ");
		for (int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}

		// Declare a sum variable to calculate the sum of the array.
		int sum = 0;

		// Iterating all array element to calculate the sum
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}

		// Printing the calculated total sum
		System.out.println("The total sum of the given array: " + sum);

	}

}

OUTPUT:

Enter the size of the Array:
5
Enter 5 element(s) of the Array:
1
2
5
9
3
The total sum of the given array: 20

See also: Java Program to Calculate Average Using Array

Java logical programs list


Java Basic Programs

Java String Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *