Loading...

Arrays in C#

Learn arrays in C#, including declaration, indexing, looping through elements, and common array operations with examples.

In C#, arrays are used to store multiple values of the same type consecutively in memory. Indexing provides fast access to elements. This article provides a detailed introduction from array declarations to multi-dimensional arrays, as well as practical examples using Array class methods.


What is an Array?

An array is a structure where data of the same type is stored in consecutive memory cells. Each element is accessed using an index number. Indexes start at 0.


int[] numbers = new int[5]; // an int array with 5 elements

Declaring Arrays and Default Values

When declaring an array, its size is specified. If no values are assigned, default values are used:


string[] names = new string[3];
Console.WriteLine(names[0]); // null

Assigning and Accessing Array Elements (Indexing)

Elements are accessed by index. Since indexes start at 0, the last element is located at Length - 1.


int[] grades = new int[5];
grades[0] = 85;
grades[1] = 90;
grades[2] = 70;
grades[3] = 75;
grades[4] = 60;

Console.WriteLine(grades[1]); // 90
Console.WriteLine(grades[^1]); // 60, This will give last element (Length - 1)

int[] sub_grades = grades[1..4]; // A sub array: 90, 70, 75

grades[5] = 100; // This will throw IndexOutOfRangeException

Assigning or accessing indices outside the array size throws an IndexOutOfRangeException. For example, in array[4], valid indices are 0, 1, 2, 3. Values like -1, 4, or 5 will cause an error. The first element is always accessed with index 0.


Array Initialization Shortcuts

You can assign values directly while creating an array.


int[] numbers = { 10, 20, 30 };
var letters = new char[] { 'A', 'B', 'C' };

Iterating Over Arrays with Loops

for and foreach loops are used to access array elements.


int[] numbers = { 3, 6, 9 };

// with for
for (int i = 0; i < numbers.Length; i++)
    Console.WriteLine(numbers[i]);

// with foreach
foreach (var n in numbers)
    Console.WriteLine(n);

Multi-Dimensional Arrays (2D, 3D)

Multi-dimensional arrays are used to store data in table or matrix form. Elements can be accessed using indexes or iterated with nested loops.


int[,] matrix = new int[2, 3]
{
    {1, 2, 3},
    {4, 5, 6}
};

Console.WriteLine(matrix[1, 2]); // 6

// Iterating with nested for loops
for (int i = 0; i < matrix.GetLength(0); i++) // rows
{
    for (int j = 0; j < matrix.GetLength(1); j++) // columns
    {
        Console.Write(matrix[i, j] + " ");
    }
    Console.WriteLine();
}

// Output:
6
1 2 3 
4 5 6 

Jagged Arrays

In jagged arrays, each row can have a different length. This is different from matrices.


int[][] jagged = new int[3][];
jagged[0] = new int[] {1, 2};
jagged[1] = new int[] {3, 4, 5};
jagged[2] = new int[] {6};

Console.WriteLine(jagged[1][2]); // 5

The Array Class and Useful Methods

In C#, all arrays derive from the Array class. Commonly used methods include:


int[] numbers = { 5, 2, 9, 1, 7 };

Array.Sort(numbers);    // Sorting
Array.Reverse(numbers); // Reversing
int index = Array.IndexOf(numbers, 9); // Searching for element

Console.WriteLine(index);

Sample Application: Student Grades

In the following example, students' grades are stored in an array and their average is calculated.


int[] grades = { 80, 70, 95, 60, 100 };

int total = 0;
foreach (var g in grades)
    total += g;

double average = (double)total / grades.Length;
Console.WriteLine($"Average: {average}");

TL;DR

  • Arrays store values of the same type consecutively in memory.
  • Indexes start at 0; default values are the type's default.
  • You can iterate through arrays with for and foreach.
  • Multi-dimensional and jagged arrays are supported.
  • The Array class provides useful array methods.

Sample Application: Contestant Scores

In this example, the number of contestants and each contestant's score are entered by the user. The total and average scores are then calculated. Input values are validated with int.TryParse to ensure they are valid integers.


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] scores = null;
        int count = 0;
        Console.Write("Number of contestants: ");

        // The input from the console is entered as a string and converted to int
        if (!int.TryParse(Console.ReadLine(), out count))
        {
            // If it cannot be converted, end program with this warning
            Console.WriteLine("\n\nA non-integer value was entered.");
            return;
        }
        else if (count > 10 || count < 3)
        {
            // If converted but the value is greater than 10 or less than 3, it is considered invalid
            Console.WriteLine("\n\nInvalid number of contestants entered.");
            return;
        }

        // If valid, create an array with the given size
        scores = new int[count];
        int i = 0;

        // Loop starts
        while (i < scores.Length)
        {
            // Each contestant's score is entered
            Console.Write($"{i + 1}. contestant: ");
            if (!int.TryParse(Console.ReadLine(), out scores[i]))
            {
                // If entered value is invalid again, terminate loop with this warning
                Console.WriteLine("\n\nA non-integer value was entered.");
                break;
            }
            i++;
        }

        // After loop ends, print total and average
        Console.WriteLine($"Total score: {scores.Sum()}");
        Console.WriteLine($"Average score: {scores.Average()}");
    }
}

Related Articles