How to calculate sum of array elements in Java

In today's coding problem, we'll see how to write a program to calculate the sum of array elements in Java. You need to write a method which will accept an integer array and it should return total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed. The array can also be null or empty so make sure your solution handle those as well. In the case of a null or empty array, your program can throw IllegalArgumentException. The empty array means, an array whose length is zero or there is no element inside it. Well, that's enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.

There is no tricky thing in this program. It is particularly designed to make a new programmer familiar working with array and loop e.g. how to iterate over an array, how to retrieve elements from an array using the index, and how to write a function to return an integer.

The solution of the problem is very simple, first, you need to write code to take the input from the user. Since you cannot take an array as input from command line, you need to take each element in store in the array you are going to pass to the sum() method. This method takes an array and returns the sum of its elements. For the sake of simplicity it is not throwing IllegalArgumentException but you can code it by yourself. Just do the check before calculating sum in the for loop.




Java Program to calculate sum of array elements in Java

Here is our complete Java program to calculate the sum of all elements of given array. It uses Scanner to take user input fro command prompt and enhanced for loop of Java 5 to loop over array. In each step we add the current element into sum variable and once the iteration finish we return this value to the caller. This the sum of all elements of given array.

Java Program to calculate sum of array elements


import java.util.Scanner;

/*
 * Java Program to calculate sum of array elements
 * input = [1, 2, 3, 4, 5, 6]
 * output = 21
 */

public class ArraySumProblem {

  public static void main(String[] args) {

  System.out.println("Welcome to Java program to calculate sum of elements in an array");
  System.out.println("Please enter the length of array?");

  Scanner scnr = new Scanner(System.in);
  int length = scnr.nextInt();
  int[] input = new int[length];

  System.out.println("Please enter elements of array");
  for (int i = 0; i < length; i++) {
  input[i] = scnr.nextInt();
  }

  int total = sumOfElements(input);
  System.out.println("Sum of all elements of array is " + total);
  scnr.close();
  }

  /**
  * A Java method to run sum of all elements of given array
  * 
  * @param array
  * @return sum of all elements of int array
  */
  public static int sumOfElements(int[] array) {
  int sum = 0;
  for (int i : array) {
  sum = sum + i;
  }
  return sum;
  }
}

Output
Welcome to Java program to calculate sum of elements in an array
Please enter the length of an array?
4
Please enter elements of array
1
2
2
3
Sum of all elements of array is 8

Welcome to Java program to calculate sum of elements in an array
Please enter the length of an array?
6
Please enter elements of array
202
34
56
6
5
46
Sum of all elements of array is 349

That's all about how to calculate the sum of array elements in Java. It's one of the simplest Java programming exercises but very good to build command over programming constructs. At the beginner level, these small program helps you to gain confidence and learn fast. If you seriously want to develop your coding sense and understand data structure and algorithms, you should start with these basic problems given below and move to more advanced problems given in Algorithm Design Manual by Steven Skiena.

How to calculate sum of array elements in Java


Other Java Programing exercises for Beginners
  • How to remove duplicate elements from the array in Java? (solution)
  • How to reverse an array in place in Java? (solution)
  • How to check if a year is a leap year in Java? (solution)
  • How to print Fibonacci series in Java (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to check if given number is prime in Java (solution)
  • How to check if two given Strings are Anagram in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to find if given Integer is Palindrome in Java? (solution)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to find the highest occurring word from a given file in Java? (solution)
  • How to count vowels and consonants in given String in Java? (solution)
  • How to implement Linear Search in Java? (solution)
  • How to check if given String is palindrome or not in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to implement binary search in Java? (solution)
  • How to reverse words in a given String in Java? (solution)
  • How to calculate Area of Triangle in Java? (program)


Further Reading

No comments:

Post a Comment