Home » Java Basics » for loop » Sum Array of Numbers with for loop

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Sum Array of Numbers with for loop

This is an example of how to get the sum of the numbers in an array using a for loop. The for statement provides a compact way to iterate over a range of values. Getting the sum using a for loop implies that you should:

  • Create an array of numbers, in the example int values.
  • Create a for statement, with an int variable from 0 up to the length of the array, incremented by one each time in the loop.
  • In the for statement add each of the array’s elements to an int sum.

Let’s take a look at the code snippet that follows:
 

package com.javacodegeeks.snippets.basics;

public class SumArrayWithForLoop {
	
	public static void main(String[] args) {
		
		// array to sum
		int[] numbers = new int[]{ 10, 10, 10, 10};
		 
		int sum = 0;
		 
		for (int i=0; i < numbers.length ; i++) {
			sum = sum + numbers[i];
		}
		 
		System.out.println("Sum value of array elements is : " + sum);
		
	}

}

Output:

Sum value of array elements is : 678

  
This was an example of how to get the sum of the numbers in an array using a for loop in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
saleh
saleh
4 years ago

sum numbers of array elements is: 40

Cris
Cris
2 years ago

This helped me thank you

Sonal
Sonal
1 year ago

What is th summation of numbers 1 -10 in for loop???