Contenido del Curso
C# Basics
C# Basics
Looping through Arrays
It is very useful to be able to quickly go through all the elements of an array and perform some operation on them or extract their values.
There are a number of ways we can do that however the most common is using the for
and foreach
loops.
In the case of using the for
loop, we can use the loop's i
variable for indexing:
main
In the above code we wrote the condition i < 5
where we chose 5
as the limit. Instead of manually counting the number of elements we can also use the Length
attribute of the arrays to access the length (size) of an array:
main
Using the length attribute the loop will look something like this:
main
We can also output the numbers in reverse by modifying the loop to run in the opposite direction:
main
We initiate i
with the value numbers.Length - 1
, because the index of the last element of an array is 1
less than the size of that array, so in this case the loop variable will start from value 9
. The loop condition i >= 0
ensures that the loop continues till i
reaches 0
. We decrement the value of i
every iteration.
Another slightly easier method of looping through arrays is by using the foreach
loop. The syntax of a foreach loop is as follows:
main
For-example:
main
The foreach
loop is simpler than the for
loop however the difference is that we cannot modify the original elements of the array in a foreach
loop. If we try to assign a new value to n
in the above code, the compiler will show an error. However, it is possible in the for loop, since we know the indices of the elements we can modify the array:
main
¿Todo estuvo claro?