Foreach: The foreach statement repeats a group of embedded statements for each element in an array or an object collection.
This C# Program Finds the Average Values of all the Array Elements.
Numbers generated by Random class.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Random rand = new Random(); int sum = 0; int[] numbers = new int[10]; for (int i = 0; i < numbers.Length; i++) { numbers[i] = rand.Next(100); } foreach (int number in numbers) { sum += number; } double avarage = (double)sum / numbers.Length; Console.WriteLine("sum:{0} \nNumbers Count:{1} \nAvarage:{2}", sum, numbers.Length,avarage ); Console.ReadLine(); |
Output:
Online Code: