Книга: C# 2008 Programmer
Accessing Array Elements
Accessing Array Elements
To access an element in an array, you specify its index, as shown in the following statements:
int[] num = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine(num[0]); //---1---
Console.WriteLine(num[1]); //---2---
Console.WriteLine(num[2]); //---3---
Console.WriteLine(num[3]); //---4---
Console.WriteLine(num[4]); //---5---
The index of an array starts from 0 to n-1. For example, num
has size of 5 so the index runs from 0 to 4.
You usually use a loop construct to run through the elements in an array. For example, you can use the for statement to iterate through the elements of an array:
for (int i = 0; i < num.Length; i++)
Console.WriteLine(num[i]);
You can also use the foreach
statement, which is a clean way to iterate through the elements of an array quickly:
foreach (int n in num)
Console.WriteLine(n);