How to Get the Sum of an Array of Numbers Using Java

Java


In this article, we show how to get the sum of an array of numbers using Java.

So we use a for loop to loop through all the elements of the array. We then have a variable tallying up all of the elements in the array.

This code how to find the sum of an array in Java is shown below.




Java Output

The total of the array is 199.99


So we create a class named Arraysum.

We then create the main method, which is the point at which the execution of the program begins.

We then create an array named prices of type double. We assign to the array some values.

We then create another variable total, which a variable keeps an ongoing sum of all the elements of an array in the for loop we create.

Underneath this, we then have our for loop.

In this for loop, we declare an int named i. We initialize i to a value of 0, because an array starts at an index of 0. We want to start at the first element of an array (index 0) and go until the last element. The last element of an array is equal to the length of the array minus one. Therefore, we make the for loop stop at this value. We put i++ because in a for loop, the index increases by 1 with each new value. We want to go through all the elements in the array, so we increement by 1 in the for loop.

In the body of the for loop, we have the statement, total += prices[i];

This means that every time we go through an element in the array prices, the value of the element gets added to the total variable. By the time we loop through the entire array, all the values in the array gets added to the total variable, and we have the total sum of the array.

We then output the array. Since the total of the values in the array is equal to 199.99, this is the value we get at the output.

And this is all that is required to get the sum of an array of numbers using Java.


HTML Comment Box is loading comments...