Arrays

Lesson 11
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, an array is a collection of variables of the same data type that are stored in contiguous memory locations. Arrays can be of any data type, including integers, doubles, booleans, strings, and even custom classes. The length of an array is fixed at the time of its creation, meaning that you cannot add or remove elements from an array after it has been created.

Here’s an example of an integer array in C#:


int[] numbers = new int[5];

In this example, we’re declaring an array called numbers that can store 5 integers. The new keyword is used to allocate memory for the array, and int[5] specifies that the array should be of type int and should have a length of 5.

We can assign values to the elements of the array using an index, which starts at 0 for the first element:


numbers[0] = 2;
numbers[1] = 5;
numbers[2] = 10;
numbers[3] = 15;
numbers[4] = 20;

In this example, we’re assigning the values 2, 5, 10, 15, and 20 to the elements of the numbers array using their indices.

We can also initialize the values of an array when we declare it:


int[] numbers = {2, 5, 10, 15, 20};

In this example, we’re initializing the numbers array with the values 2, 5, 10, 15, and 20.

We can use a loop to access the elements of the array and perform operations on them. For example, we can use a for loop to calculate the sum of the elements of the array:


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

In this example, we’re using a for loop to iterate over the elements of the numbers array using the Length property, which returns the number of elements in the array. We’re using the += operator to add each element of the array to the sum variable.