Previous lesson starts with one-dimensional array. In this lesson we’ll review arrays more closely.

# foreach

Performs the specified action for each element in an array.

Following example shows how to handle array with foreach loop.

It takes array elements one by one, prints it and increments counter inside a loop’s body.

# Find maximum element of array

Such simple task can be completed with for loop as well as with for loop.

Let’s try it with foreach first.

And now I’ll show you how ‘for’ can be better for this in case you need more functionality rather than just find some element.

This example demonstrates that you can not only find the maximum element but its index as well.

# Two-dimentional arrays

Actually it’s just a matrix. E.g.: in C# 2d array I.e. matrix can be defined as:

# Sum of array elements

Let’s review an example how to sum 2d array.

Now, let’s try to sum main diagonal elements of 5*5 matrix.

Well, now let’s calculate both diagonals.

# Bubble sorting

This task can be done with for loop.

for and foreach benefits:

• foreach - elegant looking

• for - provides additional information - an index of the current element.