Arrays in C#

In C#, an array is a data structure that allows you to store a fixed-size collection of elements of the same type. Arrays are useful for storing and accessing multiple values of the same data type efficiently. Here’s how arrays work in C#:

Declaration and Initialization:

We declare an array by specifying the type of elements it will hold, followed by square brackets [] and a name for the array. We can then initialize the array by assigning values to it.

// Declaration and initialization of an integer array with 5 elements
int[] numbers = { 1, 2, 3, 4, 5 };

Accessing Elements:

We can access individual elements of an array using their index. Array indices in C# start from 0.

int thirdNumber = numbers[2];  // Accessing the third element (index 2) of the array
Console.WriteLine(thirdNumber);  // Output: 3

Length of Array:

We can find the length of an array using the Length property.

int length = numbers.Length;  // Length of the array
Console.WriteLine(length);  // Output: 5

Modifying Elements:

We can modify elements of an array by assigning new values to specific indices.

numbers[3] = 10;  // Modifying the fourth element of the array

Iterating Over Array:

We can loop through the elements of an array using loops like for or foreach.

// Using a for loop to iterate over the elements of the array
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

// Using a foreach loop to iterate over the elements of the array
foreach (int num in numbers)
{
    Console.WriteLine(num);
}

Multi-dimensional Arrays:

C# also supports multi-dimensional arrays, allowing us to store elements in multiple dimensions, such as 2D arrays (arrays of arrays) or jagged arrays (arrays of arrays of varying lengths).

// 2D array
int[,] matrix = new int[3, 3];
matrix[0, 0] = 1;
// ...

// Jagged array
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };

Arrays are fundamental in C# programming, offering a convenient way to work with collections of data. They are widely used in various applications and algorithms.

Leave a Comment

Your email address will not be published. Required fields are marked *