Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Example

Result

Code Block
languagec#
        string[] student = { "Selvyn", "Ale", "Sam" };

        for (int idx = 0; idx < student.Length; idx++)
        {
            Console.WriteLine($"{idx}: {student[idx]}");
        }

The array has been created with a fixed number of items

We use a for loop to iterate across the items in the array. Each array has a Length property that can be used to determine the size of the array.

Accessing items within the array is done through the index operator []. Arrays are zero indexed. The value used in within the index operator must >= 0 and <= array size -1

Code Block
        string[] student = new string[3];

        student[0] = "Selvyn";
        student[1] = "Ale";
        student[2] = "Sam";

        for (int idx = 0; idx < student.Length; idx++)
        {
            Console.WriteLine($"{idx}: {student[idx]}");
        }

The array is created with a fixed size but the items are all empty strings

Populating each entry in the array

Use the for loop to access the items in the array.

Code Block
        int[] numbers = new int[] { 3, 14, 15, 92, 6 };
        
        foreach (int number in numbers)
        {
            Console.Write($"{number} ");
        }

The foreach keyword foreach statement: enumerates the elements of a collection and executes its body for each element of the collection.

In this example, the array is created with a fixed number of items. In the foreach satement, each item in numbers is projected one by one into the number variable. Each time a value from numbers is projected into the number the code block is executed with the current value in number. This repeats until all items within numbers have been exhausted.