๐ŸŽ“ A1Learner
๐Ÿ”

C# Arrays

An array is a variable that holds many values of one type in a fixed order. Each value sits at an index, and the first index is 0.

Reading by index

The values sit at indexes 0, 1, and 2. The prints read the first and the last value.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] scores = { 70, 85, 90 };
        Console.WriteLine(scores[0]);
        Console.WriteLine(scores[2]);
    }
}

Changing one element

The assignment writes a new value at index 1. The print reads that same index back.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] scores = { 70, 85, 90 };
        scores[1] = 95;
        Console.WriteLine(scores[1]);
    }
}

Length and last

Length counts the elements in the array. The last element sits one index below that count.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] scores = { 70, 85, 90 };
        Console.WriteLine(scores.Length);
        Console.WriteLine(scores[scores.Length - 1]);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] temps = { 21, 23, 19, 25 };
        int warmest = temps[0];
        int sum = 0;
        for (int i = 0; i < temps.Length; i++)
        {
            if (temps[i] > warmest)
            {
                warmest = temps[i];
            }
            sum += temps[i];
        }
        Console.WriteLine("Warmest: " + warmest);
        Console.WriteLine("Average: " + (sum / temps.Length));
    }
}

Key points

  • Square brackets after the type mark an array.
  • The first element sits at index 0.
  • An index in square brackets reads one element.
  • An index in square brackets can also change one element.
  • Length gives the count of elements in the array.
  • The last index is the Length value minus 1.

In this example, the loop visits each temperature in order. It keeps the largest value seen in warmest. It also adds each value to sum, and the sum is 88. Integer division of 88 by 4 gives 22. The first printed line is "Warmest: 25". The second printed line is "Average: 22".

Note

Printing an array prints its type name, so elements are printed one at a time.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What is the index of the first element in an array?