Java for each loop sum integers in an array

Description

Java for each loop sum integers in an array

public class Main
{
   public static void main(String[] args) 
   {/*  w  w  w  .  java 2 s  . c  o  m*/
      int[] array = {8, 6, 4, 10, 3, 5};
      int total = 0;

      // add each element's value to total
      for (int number : array)
         total += number;

      System.out.printf("Total of array elements: %d%n", total);
   } 
}

The following code uses the normal for loop to sum the elements of an array.

public class Main
{
   public static void main(String[] args)
   {/*from  w  w  w  . j a  v a  2s .com*/
      int[] array = {7, 6, 4, 10, 3, 12};
      int total = 0;

      // add each element's value to total
      for (int counter = 0; counter < array.length; counter++)
         total += array[counter];

      System.out.printf("Total of array elements: %d%n", total);
   }    
}



PreviousNext

Related