Sums the values in an array using a foreach loop
/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// ForEach.cs -- Sums the values in an array using a foreach loop
//
// Compile this program with the folowing command line
// C:>csc ForEach.cs
//
namespace nsForEach
{
using System;
public class ForEach
{
static public void Main ()
{
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
int [] Arr = new int [10];
for (int x = 0; x < Arr.Length; ++x)
{
Arr[x] = rand.Next () % 100;
}
int Total = 0;
Console.Write ("Array values are ");
foreach (int val in Arr)
{
Total += val;
Console.Write (val + ", ");
}
Console.WriteLine ("and the average is {0,0:F1}",
(double) Total / (double) Arr.Length);
}
}
}
Related examples in the same category