# Arrays in C#

In simple English, array means collection. In C# also, an array is a collection of similar types of data. For example, an array of int is a collection of integers, an array of double is a collection of doubles, etc.

Suppose we need to store the marks of 50 students in a class and calculate the average marks. Declaring 50 separate variables will do the job but no programmer would like to do so. And here comes the array in action.

## Declaration and Initialization of Array

The syntax for declaring an array is:

type[] arrayName = new type[array_size];

For example, take an array of 6 integers n. We will declare it as:

int[] n = new int[6];

[ ] is used to denote an array.

int[] n means that n is an array of integers. n is the name of the array.

new keyword is used to allocate space in the memory of the computer. new int[6] means that the compiler will allocate space for 6 integers in the memory. Here, 6 is the size of the array.

Array uses a contiguous memory location. Thus if the address of the first element of an array of integers is X then the address of the second element will be X+4 (4 is the size of one integer) and third will be X+4+4 and so on. This means that the memories of all elements of an array are allocated together and are continuous.

We can also declare and initialize an array at the same time.

int[] n = new int[]{2, 3, 15, 8, 48, 13};

Even this will work:

int[] n = {2, 3, 15, 8, 48, 13};

In these cases, we are declaring and assigning values to the array at the same time. Hence, no need to specify the array size because the compiler already knows the elements of the array and thus the size of it.

Following is the pictorial view of the array.

 element 2 3 15 8 48 13 index 0 1 2 3 4 5

0, 1, 2, 3, 4 and 5 are the indices of the elements of the array. It is like these are the identities of 6 different elements of the array. Index starts from 0. So, the first element of an array has an index of 0. We access the elements of an array by writing arrayName[index].

Thus in the above example, n[0] is 2, n[1] is 3, n[2] is 15, etc.

So, we have made an array of integers and then accessed its elements using arrayName[index]. Now, we can use these separate elements as different variables. Thus, we didn't have to declare 6 different variables.

By writing int[] n= {2, 4, 8}; , we can declare and initialize the array at the same time. But when we declare an array like int[] n = new int[3];, we need to assign the values to it separately. Because new int[3] will definitely allocate the space of 3 integers in the memory but we haven't assigned any values to them yet.

We already know that we can access the elements of an array as different variables using their indices (arrayName[index]). So, we can easily assign values to each of the element of the array as we do with variables.

n[0] = 2;, n[1] = 4; and n[2] = 8; will assign the vaules to the first, second and the third element of the array n respectively.

Just like a variable, an array can be of other data types also.

double[] d[] = { 1.1, 1.4, 1.5};

Here, d is an array of doubles.

First, let's see the example to calculate the average of the marks of 3 students. In the example, marks[0], marks[1] and marks[2] represent the marks of the first, second and third student respectively.

using System;

class Test
{
static void Main(string[] args)
{
int[] marks = new int[3]; //array of 3 integers
double average; //variable to store average marks

Console.WriteLine("Enter marks of first student");
marks[0] = Convert.ToInt32(Console.ReadLine()); //setting value of marks[0]

Console.WriteLine("Enter marks of second student");

Console.WriteLine("Enter marks of third student");

average = (marks[0] + marks[1] + marks[2])/3.0;

Console.WriteLine($"Average marks : {average}"); } }  Enter marks of first student 23 Enter marks of second student 25 Enter marks of third student 31 Average marks : 26.3333333333333 Here, you have seen a working example of an array. We treated the elements of the array in a similar way as we had treated normal variables. We can get the length (size) of any array using the Length property. For example, for an array n, int[] n = new int[3], n.Length will be 3. Let's look at one more example. using System; class Test { static void Main(string[] args) { int[] n = new int[10]; /* initializing elements of array n */ for(int i=0; i<n.Length; i++) { Console.WriteLine($"Enter value of n[{i}]");
}

for(int i=0; i<n.Length; i++)
{
Console.WriteLine($"n[{i}] = {n[i]}"); } } }  Enter value of n[0] 23 Enter value of n[1] 25 Enter value of n[2] 31 Enter value of n[3] 1 Enter value of n[4] 33 Enter value of n[5] 35 Enter value of n[6] 76 Enter value of n[7] 47 Enter value of n[8] 74 Enter value of n[9] 45 n[0] = 23 n[1] = 25 n[2] = 31 n[3] = 1 n[4] = 33 n[5] = 35 n[6] = 76 n[7] = 47 n[8] = 74 n[9] = 45 The above code was just to make you familiar with using loops with an array because you will be doing this many times later. The code is simple, i starts from 0 because the index of an array starts from 0 and goes up to 9 (for 10 elements, index of the array will also go upto 9). So, i goes up to 9 and not 10 (i<n.Length will be i<10). So in the above code, n[i] will be n[0], n[1], n[2], ...., and n[9]. There are two for loops in the above example. In the first for loop, we are taking the values for the different elements of the array from the user one by one. In the second for loop, we are printing the values of the elements of the array. Let's go to the first for loop. In the first iteration, the value of i is 0, so n[i] is n[0]. Thus by writing n[i] = Convert.ToInt32(Console.ReadLine());, the user will be asked to enter the value of n[0]. Similary in the second iteration, the value of i will be 1 and n[i] will be n[1]. So n[i] = Convert.ToInt32(Console.ReadLine()); will be used to input the value from the user for n[1] and so on. i will go up to 9, and so indices of the array (0, 1, 2, ..., and 9). ## Passing Array to Method In C#, we can pass an element of an array or the full array as an argument to a method. Passing an element of an array is the same as passing a normal variable. Let's see an example of doing so. using System; class Test { static void Display(int a) { Console.WriteLine(a); } static void Main(string[] args) { int[] n = {20, 30, 23, 4, 5, 2, 41, 8}; Display(n[2]); } }  23 So, it is exactly like passing a simple variable to a method because an element of an array is just like a simple variable. ### Passing Entire Array to Method We can also pass a whole array to a method. We know that a function accepts data of particular data type when we mention the data type in the parameter of the function. For example, Display(int a) will take an integer, Abc(int a, double b) will take one integer and one double, etc. Similarly, to make a function accept arrays, we will use [] with its data type. For example, Display(int[] a) will take an array of integers. Now, we can simply pass an array as an argument to this function. Let's take an example. using System; class Test { static double Average(double[] a) //Average is taking an array of doubles { double avg, sum = 0; for(int i=0; i<a.Length; i++) { sum+= a[i]; } avg = sum/8; return avg; } static void Main(string[] args) { double[] n = {20.6, 30.8, 5.1, 67.2, 23, 2.9, 4, 8}; double b = Average(n); //passing array to method Average Console.WriteLine($"Average of numbers = {b}");
}
}

Average of numbers = 20.2

Average(double[] a) → It is the method that is taking an array of doubles. And the rest of the body of the method is performing accordingly.

double b = Average(n) → We are passing the array n as the argument to the function Average.

## foreach Loop

There is one more loop available in C# - foreach loop. It is used to iterate over an array and makes iterating over arrays easier. Let's see an example of this.

using System;

class Test
{
static void Main(string[] args)
{
int[] ar = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

foreach(int m in ar)
{
Console.WriteLine(m);
}
}
}

1
2
3
4
5
6
7
8
9
10

This is very simple. Here, the variable m will go to every element of the array ar and will take its value.

So, in the first iteration, m is the 1st element of the array ar i.e. 1.

In the second iteration, it is the 2nd element i.e. 2 and so on. Just focus on the syntax of this for loop, the rest of the part is very easy.

Let's take an example of finding the largest number of an array.

using System;

class Test
{
static void Main(string[] args)
{
int[] a = {23, 434, 234, 543, 350, -23, 133, 54, 3, -34, -124};

int max = a[0]; //setting first element of array as maximum number

foreach(int i in a)
{
if(i > max) //if current element of array is greater than the current maximum value
max = i; //changing the value of variable max
}

Console.WriteLine(max);
}
}

543

In this example, we are first setting the first element of the array a as the maximum value - max = a[0]. After this, we are iterating over each element of the array and comparing it with the variable max. If the value is greater than the value of max, we are changing the value of max to that element of the array. Ultimatley, max will have the maximum value of all elements of the array.

## Returning Array from Method

We can also return an array from a method like we return any other data type. To return an integer from a function Abc, we write static int Abc(). Similarly, to return an array from a function Def, we would write static int[] Def(). Let's look at an example.

using System;

class Test
{
static int[] NaturalNumber(int n) //method for get first n natrual numbers
{
int[] a = new int[n];
for(int i=0; i<a.Length; i++)
{
a[i] = i+1; //first natural number will be 1, second will be 2 and so on.
}
return a; //returning array
}

//function to display array
static void Display(int[] a)
{
foreach(int i in a)
Console.Write(\$"{i}\t");
Console.Write("\n");
}

static void Main(string[] args)
{
int[] a = NaturalNumber(10);

Display(a);
}
}

1  2 3 4 5 6 7 8 9 10

In this example, the function NaturalNumber is returning an array - static int[] NaturalNumber(int n). Firstly, we are making an array inside this function - int[] a = new int[n]; and then setting its elements to store natural number starting from 1 - a[i] = i+1;. So, a[0] will store 1, a[1] will store 2 and so on. At last, we are returning this array - return a;.

## Params

Suppose you are writing a code and you need to make a method to find the sum of a few integers but the number of integers is not fixed. We can handle these kinds of situations using the params keyword. params is used to pass a variable number of arguments to a method. All the passed arguments will be stored in an array and then we can access that array inside the method.

Let's take an example where the function Abc is going to take a variable number of arguments, we would define the function as - Abc(params int[] a). Now, all the passed integers to the function will be stored in the array a and we can easily access the array a to access all the passed arguments.

Let's take an example.

using System;

class Test
{
static int FindSum(params int[] a)
{
int sum = 0;
foreach(int i in a)
{
sum = sum+i;
}
return sum;
}

static void Main(string[] args)
{
int a = FindSum(1, 2, 3, 4);
int b = FindSum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Console.WriteLine(a);
Console.WriteLine(b);
}
}

10
55

In the above example, the function FindSum is taking a variable number of arguments - (params int[] a) and we are accessing all those numbers as elements of the array a inside the function.

int a = FindSum(1, 2, 3, 4);
int b = FindSum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

You can see that different number of arguments in these two lines.

## Methods in Array

There are many useful predefined methods available for us to use for an array. All these methods are inside Array class, so we wil access these methods using Array.MethodName(). Some of the important methods are:

### IndexOf

IndexOf is used to get the index of any element of an array. Let's take an example.

using System;

class Test
{
static void Main(string[] args)
{
int[] a = {1, 2, 3, 4, 5};
Console.WriteLine(Array.IndexOf(a, 3));
}
}

2

### Reverse

Reverse reverses the elements of an array. So, the first element of an array will become the last and last will become the first.

using System;

class Test
{
static void Main(string[] args)
{
int[] a = {1, 2, 3, 4, 5};
Array.Reverse(a);

foreach(int i in a)
Console.WriteLine(i);
}
}

5
4
3
2
1

### Sort

It is used to arrange elements of the array in an acesnding order.

using System;

class Test
{
static void Main(string[] args)
{
int[] a = {4, 1, 5, 3, 2};
Array.Sort(a);

foreach(int i in a)
Console.WriteLine(i);
}
}

1
2
3
4
5

There are many other methods also. You can see the full list on offical documentation.

## Reference Type and Value Type

Data types like int, double, etc. are value type. It means that a value is stored in the mermory of a computer. That's why we need to pass these data types by their references when we need to change their values inside a method.

On the other hand, arrays, strings, classes and delegates are reference type. It means that there reference is stored in the memory and we can normally pass it to a method and any changes made in a method will be also reflected outside it.

Let's take an example.

using System;

class Test
{
static void Change(int[] a)
{
a[0] = 1;
}

static void Main(string[] args)
{
int[] a = {4, 2, 3, 4, 5};

Change(a);

foreach(var i in a)
Console.WriteLine(i);
}
}

1
2
3
4
5

You can see that the change made to the array inside the method is also reflecting outside it.