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.
sum numbers of array elements is: 40
This helped me thank you
What is th summation of numbers 1 -10 in for loop???