Arrays & Loops
It’s occasionally necessary to iterate through the elements of an array, making element assignments based on certain calculations. This can be easily done using loops.
For example, you can declare an array of 10 integers and assign each element an even value with the following loop:
int[ ] a = new int[10];
for (int N = 1; N < 10; N++) {
a[N] = N*2;
}
We can also use a loop to read the values of an array.
For example, we can display the contents of the array we just created:
The Code:

The Output of Your Program:

And if you continue press the F5 this is the output:

This will display the values of the elements of the array.
The variable N is used to access each array element.
The last index in the array is 8, so the for loop condition is N<10.
The foreach Loop
The foreach loop provides a shorter and easier way of accessing array elements.
The previous example of accessing the elements could be written using a foreach loop:
The Code:

The Output of Your Program:

The data type of the variable in the foreach loop should match the type of the arrayelements.
Often the keyword var is used as the type of the variable, as in: foreach (var N in a). The compiler determines the appropriate type for var.
Arrays
The following code uses a foreach loop to calculate the sum of all the elements of an array:
The Code:

The Output of Your Program:

To review, we declared an array and a variable sum that will hold the sum of the elements.
Next, we utilized a foreach loop to iterate through each element of the array, adding the corresponding element’s value to the sum variable.
The Array class provides some useful methods that will be discussed in the coming lessons.
