Pages

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.

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.

1 comment:

i want to declare two single dimension array or size in 4 (both) eg. int []a={1,2,3.4}second is int []b={5,6,7,8}; and now i want the sum of array element in other array call ed int [] c= new int[4];in this array i want like {6,8,10,12}can u show me the way to do it ?