# Arrays

An array is a collection of similar types of data. For example:

Suppose we need to record the age of 5 students. Instead of creating 5 separate variables, we can simply create an array:

<figure><img src="https://3825307495-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FeGOQNkvFZqkwT6hzD7EL%2Fuploads%2FfVeCqyDKGfAep4aLG2rn%2FElements%20of%20an%20array.png?alt=media&#x26;token=30256d91-6ed8-4556-a076-33433de5df51" alt=""><figcaption><p>Elements of an array</p></figcaption></figure>

### Array Declaration

```csharp
datatype[] arrayName;
```

Here,

`dataType` - data type like int, string, char, etc.

`arrayName` - it is an identifier

**Let's see an example,**

```csharp
// declare an array
int[] age;

// allocate memory for array
age = new int[5];
```

Here, we have created an array named age. It can store 5 elements of int type.

### Array initialization

In C#, we can initialize an array during the declaration. For example:

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

Here, we have created an array named numbers and initialized it with values 1, 2, 3, 4, and 5 inside the curly braces

{% hint style="info" %}
Note that we have not provided the size of the array. In this case, the C# automatically specifies the size by counting the number of elements!
{% endhint %}

### Array indexing

We can use the index number to initialize an array in C#. For example:

```csharp
// declare an array
int[] age = new int[5];

//initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
...
```

<figure><img src="https://3825307495-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FeGOQNkvFZqkwT6hzD7EL%2Fuploads%2Fq8U9Dzh9lQDDFCP1u3mg%2FArray%20indexing.png?alt=media&#x26;token=5e82864b-3392-4080-a12f-10dca568e0a0" alt=""><figcaption><p>Array indexing</p></figcaption></figure>

As you can see from the above diagram, An array index always starts at 0.

{% hint style="info" %}
The first element of an array is at index 0. If the size of an array is 5, the index of the last element will be at 4
{% endhint %}

### Access Array Elements

We can access the elements in the array using the index of the array. For example:

```csharp
// access element at index 2
array[2];

// access element at index 4
array[4];
```

### Exercise

Complete the code to get the expected output

**Expected Output:**

```csharp
Element in first index : 1
Element in second index : 2
Element in third index : 3
```

```csharp
using System;

class Program  {
    static void Main() {

      // todo - create an array called numbers with elements 1, 2 and 3 in it

      //access first element
      Console.WriteLine("Element in first index : " + /*todo*/); 

      //access second element
      Console.WriteLine("Element in second index : " + /*todo*/);

      //access third element
      Console.WriteLine("Element in third index : " + /*todo*/);

      Console.ReadLine();

    }
}
```

### Iterating array using for loop

In C#, we can use loops to iterate through each element of an array. For example:

```csharp
class Program {
    static void Main(string[] args) {

      int[] numbers = { 1, 2, 3};
 	 
      for(int i=0; i < numbers.Length; i++) {
        Console.WriteLine("Element in index " + i + ": " + numbers[i]);
      }

      Console.ReadLine();
    }
  }
```

Output:

```csharp
Element in index 0: 1
Element in index 1: 2
Element in index 2: 3
```

{% hint style="info" %}
Here, the `Length` property of the array gives the size of the array.
{% endhint %}

### Iterating array using foreach loop

We can also use a `foreach` loop to iterate through the elements of an array. For example:

```csharp
class Program {
    static void Main(string[] args) {
      int[] numbers = {1, 2, 3};

      Console.WriteLine("Array Elements: ");

      foreach(int num in numbers) {
        Console.WriteLine(num);
      }

      Console.ReadLine();
    }
  }
```

Output

```csharp
Array Elements:
1
2
3
```

### Exercise

Find the sum and average of 5 numbers given by user:

Expected output:

```csharp
Enter Number 1
1
Enter Number 2
2
Enter Number 3
3
Enter Number 4
4
Enter Number 5
5
Given numbers are:
1 2 3 4 5 
Sum is 15 and Avg is 3
```

```csharp
using System;

class Program  {
    static void Main(string[] args) {
        int[] nums = /*todo*/
        
        for(/*todo*/){
            Console.WriteLine("Enter Number {0}", i+1);
            /*todo*/
        }   

        int sum =0;
        foreach(/*todo*/)   
            sum+=num;
        
        int avg = /*todo*/

        Console.WriteLine("Given numbers are:");
        foreach(/*todo*/)   
            Console.Write($"{num} ");

        Console.WriteLine();
        Console.WriteLine($"Sum is {/*todo*/} and Avg is {/*todo*/}");
    }
}
```

### Exercise

Find the largest word among the words entered by user

Expected Output

```csharp
How many words do you want to input?
3
Enter word no 1
computer
Enter word no 2
is
Enter word no 3
fun
Among the given words, largest word is computer
```

```csharp
using System;

class Program  {
    static void Main() {
       Console.WriteLine("How many words do you want to input?");
       int size = Convert.ToInt32(Console.ReadLine());

       /*todo - declare words array*/
       for(/*todo*/){
           Console.WriteLine($"Enter word no {i+1}");
          /*todo - store the words*/
       }

       int large =0;
       string largestWord = string.Empty;
       foreach(/*todo*/){
           if(word.Length > large){
               large = word.Length;
               largestWord = word;
           }           
       }
       Console.WriteLine($"Among the given words, largest word is {/*todo*/}");
    }
}
```
