C# Arrays

Welcome to The Coding College! In this tutorial, we’ll dive deep into arrays in C#. Arrays are one of the most fundamental data structures, enabling you to store and manage collections of data efficiently. By the end of this guide, you’ll have a thorough understanding of how to declare, initialize, and manipulate arrays in C#.

What is an Array?

An array in C# is a collection of elements of the same data type stored in contiguous memory locations. Arrays allow you to work with multiple values using a single variable, indexed by a number.

Key Features of Arrays:

  1. Fixed size (number of elements defined during initialization).
  2. Zero-based indexing (the first element is at index 0).
  3. Elements must be of the same data type.

Declaring and Initializing Arrays

Declaration Syntax:

dataType[] arrayName;

Initialization Syntax:

arrayName = new dataType[size];

Combine Declaration and Initialization:

dataType[] arrayName = new dataType[size];

Example 1: Declare and Initialize an Array

using System;

class Program
{
    static void Main()
    {
        int[] numbers = new int[5]; // Array with 5 elements

        // Assign values
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
        numbers[3] = 40;
        numbers[4] = 50;

        // Access and print values
        Console.WriteLine("First element: " + numbers[0]);
        Console.WriteLine("Second element: " + numbers[1]);
    }
}

Output:

First element: 10  
Second element: 20  

Example 2: Declare and Initialize with Values

using System;

class Program
{
    static void Main()
    {
        string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

        Console.WriteLine("Fruits List:");
        for (int i = 0; i < fruits.Length; i++)
        {
            Console.WriteLine(fruits[i]);
        }
    }
}

Output:

Fruits List:  
Apple  
Banana  
Cherry  
Date  
Elderberry  

Explanation:
The array is initialized directly with values. The Length property returns the number of elements in the array.

Types of Arrays in C#

C# supports various types of arrays for different use cases:

  1. Single-Dimensional Array:
    A simple array with one row of elements.
  2. Multi-Dimensional Array:
    Arrays with two or more dimensions, such as matrices.
  3. Jagged Array:
    An array of arrays, where each “inner” array can have different sizes.

Single-Dimensional Array

Syntax:

dataType[] arrayName = new dataType[size];

Example:

int[] numbers = { 1, 2, 3, 4, 5 };

Multi-Dimensional Array

Syntax:

dataType[,] arrayName = new dataType[rows, columns];

Example:

using System;

class Program
{
    static void Main()
    {
        int[,] matrix = {
            { 1, 2, 3 },
            { 4, 5, 6 },
            { 7, 8, 9 }
        };

        Console.WriteLine("Element at (2,2): " + matrix[1, 1]); // Output: 5
    }
}

Jagged Array

Syntax:

dataType[][] arrayName = new dataType[outerSize][];

Example:

using System;

class Program
{
    static void Main()
    {
        int[][] jaggedArray = new int[3][];
        jaggedArray[0] = new int[] { 1, 2 };
        jaggedArray[1] = new int[] { 3, 4, 5 };
        jaggedArray[2] = new int[] { 6 };

        Console.WriteLine("Element in first array: " + jaggedArray[0][1]); // Output: 2
    }
}

Accessing Array Elements

To access elements in an array, use the index of the element. Indexing starts at 0.

Example:

int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[2]); // Output: 30

Iterating Over Arrays

Using a For Loop

int[] numbers = { 1, 2, 3, 4, 5 };

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

Using a Foreach Loop

string[] colors = { "Red", "Green", "Blue" };

foreach (string color in colors)
{
    Console.WriteLine(color);
}

Common Operations with Arrays

  • Get Length of an Array:
    Use the Length property to determine the number of elements.
int[] numbers = { 10, 20, 30 };
Console.WriteLine(numbers.Length); // Output: 3
  • Sort an Array:
    Use the Array.Sort() method.
int[] numbers = { 30, 10, 20 };
Array.Sort(numbers);
  • Reverse an Array:
    Use the Array.Reverse() method.
Array.Reverse(numbers);

Conclusion

Arrays are a crucial tool in programming, providing an efficient way to store and manipulate collections of data. From single-dimensional arrays to jagged arrays, C# offers a variety of array types for different scenarios. Mastering arrays will significantly enhance your ability to build efficient applications.

For more tutorials on coding and programming, visit The Coding College and start your journey to becoming a skilled developer today!

Leave a Comment