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:

Elements of an array

Array Declaration

Here,

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

arrayName - it is an identifier

Let's see an example,

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:

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

circle-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!

Array indexing

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

Array indexing

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

circle-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

Access Array Elements

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

Exercise

Complete the code to get the expected output

Expected Output:

Iterating array using for loop

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

Output:

circle-info

Here, the Length property of the array gives the size of the array.

Iterating array using foreach loop

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

Output

Exercise

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

Expected output:

Exercise

Find the largest word among the words entered by user

Expected Output

Last updated