Misc-Java-Examples

How to calculate the sum of the numbers in an array

Posted On
Posted By admin

In this blog post, I will be explaining how you can calculate the sum of numbers in an array. Consider the following code snippet:


package demo;

public class SumDemo {

public static void main(String[] args) {
int numbers[] = {5,4,7,9,12};

int sum = 0;
for(int number:numbers){
sum += number;
}
System.out.println("sum="+sum);

}

}


 

A variable called sum is used to store the sum of numbers. It is initialized to 0. There is a for loop used. This iterates through the input list. It adds each number in the list to the sum variable.

This code will print the following output:

sum=37
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my Java course here

Also, if you'd like to test your Java knowledge, do check out my practice tests course here


If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment