4.4.1.Use the foreach loop. |
|
The foreach loop is used to cycle through the elements of a collection. |
The general form of foreach is shown here: |
foreach(type var-name in collection)
statement;
|
|
using System;
class MainClass {
public static void Main() {
int sum = 0;
int[] nums = new int[10];
for(int i = 0; i < 10; i++)
nums[i] = i;
Console.WriteLine("use foreach to display and sum the values");
foreach(int x in nums) {
Console.WriteLine("Value is: " + x);
sum += x;
}
Console.WriteLine("Summation: " + sum);
}
}
|
|
use foreach to display and sum the values
Value is: 0
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Summation: 45 |