for loop

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
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
6 years ago

sum numbers of array elements is: 40

Cris
Cris
4 years ago

This helped me thank you

Sonal
Sonal
3 years ago

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

Back to top button