Previous lesson starts with one-dimensional array. In this lesson we’ll review arrays more closely.
Agenda
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.
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.
Actually it’s just a matrix. E.g.:
in C# 2d array I.e. matrix can be defined as:
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.
This task can be done with for loop.
for and foreach benefits: