Using the foreach statement to total integers in an array in C#

using System;
 
public class ForEachExample
{
   public static void Main( string[] args )
   {
      int[] array = { 8, 6, 4, 10, 3, 7, 5, 1, 16,7 };
      int total = 0;
 
      // add each element's value to total
      foreach ( int number in array )
         total += number;
 
      Console.WriteLine( "Total of array elements: {0}", total );
   } // end Main
} // end class ForEachExample

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.