C# Arrays

In C# coding language, an array represents a group of identical data elements stored within a single variable. It does not conserve additional memory. Arrays operate using indexes, with the initial index being 0 and the final element's index being size-1.

The <style> element is styled with a linear gradient background, rounded corners, padding, and centered text. Within this element, there is an icon with a size of 3rem and a text with a font size of 1rem that is colored in #9ca3af.

Simple Array Example in C#

Let's consider an example to demonstrate the process of defining arrays.

Example

Example

using System;

class Program

{

    static void Main()

    {

        // defining an array and assigning values

        int [] num_bers = { 10, 20, 30 };

        //using for loop 	

        for (int i = 0; i < num_bers.Length; i++)

        {

            Console.WriteLine("Element at index " + i + " is: " + num_bers[i]);

        }

    }

}

Output:

Output

Element at index 0 is: 10

Element at index 1 is: 20

Element at index 2 is: 30

Explanation:

In this instance, we will illustrate the concept of an array in a straightforward manner. Initially, we declare an array of integer type called "number" and set it up with certain initial values. Subsequently, a for loop is employed to traverse through the elements of the array. Ultimately, the Console.WriteLine method is utilized to display the numbers on the console.

Here, we will explore the process of declaring, initializing, accessing, and various other operations related to arrays.

Array Declaration

In C# programming, an array is constructed by specifying the data type followed by the array name and size enclosed within square brackets .

Syntax:

It has the following syntax.

Example

data_type array_name [size];

The syntax declares an array titled array_name with a specified size.

The data_type indicates the specific data type of an array, like integer, floating point, character, and so on.

For Example:

Example

int my_arr [10];

In this example,

  • int: It represents the type of value that can be stored in an array.
  • arr: It declares the name of an array.
  • 10: It represents the size of an array.
  • Initializing an Array in C#

The array is initialized at the time of declaration. There are two common methods for initializing an array:

  • Array initialization during declaration
  • Setting values post declaration
  • a) Initializing an array during declaration

In C# programming, an array is initialized within curly brackets {} following the array declaration.

For Example:

Example

int myarr [5] = {1, 2, 3, 4, 5};

b) Assigning values after declaration

An array is created using the index as a basis, and it is set up by first declaring it.

For Example:

Let's consider a practical example to assign a value following the declaration of an array.

Example

int arr[4]; // declaration of an array

// Assigning values to each element

arr [0] = 5;

arr [1] = 10;

arr [2] = 15;

arr [3] = 20;

arr [4] = 25;

Accessing Array Elements in C#

In C# programming, indexing refers to the method of retrieving elements from an array by specifying the array name followed by the index number enclosed in square brackets (). The initial element in an index is 0, while the final element is size-1. This functionality allows for direct access, retrieval, and alteration of specific array elements.

The CSS code snippet below defines the styling for a placeholder diagram. The background is set as a linear gradient with specific color stops, and the diagram has rounded corners with padding and margins for spacing. The text is centered within the diagram, and there is an icon and text element styled within it.

Syntax:

It has the following syntax.

Example

name_of_the_array[index];

Accessing Array Elements Example in C#

Let's consider an example to demonstrate how to access elements in an array using C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        // defining an array and assigning some values

        int [] num_bers = { 10, 20, 30, 40, 50 };

        // Displaying specific elements from the array

        Console.WriteLine("The starting element at the index 0: " + num_bers[0]);

        Console.WriteLine("The middle element at the index 2: " + num_bers[2]);

        Console.WriteLine("The last element at the index 4: " + num_bers[4]);

        Console.Write("The complete array elements: ");

        for (int index = 0; index < num_bers.Length; index++)

        {

            Console.Write(num_bers[index] + " ");

        }

        Console.WriteLine(); // To move to the next line after the loop

    }

}

Output:

Output

The starting element at the index 0: 10

The middle element at the index 2: 30

The last element at the index 4: 50

Complete array elements: 10 20 30 40 50

Explanation:

In this instance, we are defining an array called numbers and proceeding to set initial values to the array elements. Subsequently, we access the values at index 0, 2, and 4 of the numbers array using numbers[0], numbers[2], and num_bers[4]. The foreach loop is employed for iterating through the numbers in the array. Ultimately, the Console.WriteLine method is utilized to display the output.

Taking inputs from the user and storing them in an Array in C#

Let's consider an illustration where we gather user inputs and save them in an array.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int[] num_bers = new int[3];

        Console.WriteLine("Enter 3 numbers:");

        for (int i = 0; i < 3; i++)

        {

            Console.Write("Number " + (i + 1) + ": ");

            num_bers[i] = Convert.ToInt32(Console.ReadLine());

        }	

        Console.WriteLine("You entered:");

        for (int i = 0; i < 3; i++)

        {

            Console.WriteLine(num_bers[i]);

        }

    }

}

Output:

Output

Enter 3 numbers:

Number 1: 5

Number 2: 10

Number 3: 15

You entered:

5

10

15

Explanation:

In this illustration, we establish an array called "numbers" with a capacity of 3 to hold three values inputted by the user. Each value is input sequentially by the user. The input is acquired using the Console.ReadLine method and then transformed into an integer using Convert.ToInt32. Subsequently, a for loop is employed to cycle through the numbers. Ultimately, the Console.WriteLine method is utilized to display the output.

Types of Arrays in C#

There are three categories of the C# Programming language. These consist of:

The <style> element includes a CSS class named "placeholder-diagram" with specific styles such as a linear gradient background, border radius, padding, margin, and text alignment. Within this class, there are also styles defined for the sub-elements ".placeholder-icon" and ".placeholder-text" to control font size, margin, and color. These styles are crucial for creating visually appealing diagrams or visual representations on a web page.

1) Single-dimensional Array

In C#, a one-dimensional array is a specific type of array capable of storing a set quantity of elements of identical data type in a particular order.

Syntax:

It has the following syntax.

Example

type arrayname = new type [size];

In this syntax,

  • type: It defines the data type of the value that the array can store.
  • arrayname: It defines the name of an array.
  • Size: It represents the size of an array.
  • C# Single-dimensional Array Example

Let's consider an example to explain the Single-dimensional array concept in C#.

Example

Example

using System;

public class ArrayExample

{	

    public static void Main(string[] args)

    {

        // defining and initializing an array of size 5

        int [] con = new int[5];

        con [0] = 10;

        con [2] = 20;

        con [4] = 30;

        // Traversing the array and printing elements

        for (int i = 0; i < con.Length; i++)

        {

            Console.WriteLine("Element at index " + i + ": " + con[i]);

        }

    }

}

Output:

Output

Element at index 0: 10

Element at index 1: 0

Element at index 2: 20

Element at index 3: 0

Element at index 4: 30

Explanation:

In this instance, a one-dimensional array is being utilized in C#. Initially, the array is defined as 'numbers' and each element is assigned a value individually. Subsequently, a foreach loop is employed to cycle through the elements in the array. Ultimately, the Console.WriteLine method is utilized to display the results.

C# Array Example: Initialization and Declaration at the same time

There are three methods to set up an array during its declaration.

Example

int [] arr = new int[5]{1, 2, 3, 4, 5};

We can omit the size of an array.

Example

Int[] arr = new int[] {10, 20, 30, 40, 50};

We can omit the new operator also.

Example

Int arr[] = {10,20,30,40,50};

Let's explore an example of an array where we declare and initialize the array simultaneously.

Example

Example

using System;  

public class ArrayExample  

{  

    public static void Main(string[] args)  

    {  

        int[] arr = { 100, 200, 300, 400, 500 };//defining and Initialization of array  

        //traversing array  

        for (int i = 0; i < arr.Length; i++)  

        {  

            Console.WriteLine(arr[i]);  

        }  

    }  

}

Output:

Output

100

200

300

400

500

Explanation:

In this instance, we start by declaring an array of integers called arr and proceed to assign it initial values. Subsequently, we employ a for loop to cycle through the numerical values. Ultimately, we utilize the Console.WriteLine method to display the numbers.

C# Array Example: Traversal Using foreach loop

We can iterate through the elements of an array using a foreach loop, which retrieves each array element individually.

Example

Example

using System;

class Program

{

    static void Main()

    {

        // defining and initialize a string array

        string[] fruits = { "Apple", "Banana", "Cherry", "Date" };

        // Traverse the array using foreach loop

        Console.WriteLine("The Fruits in an array:");

        foreach (string fruit in fruits)

        {

            Console.WriteLine(fruit);

        }

    }

}

Output:

Output

The Fruits in an array:

Apple

Banana

Cherry

Date

Explanation:

In this instance, we construct a demonstrative array model. Initially, we declare an array of type string named fruits. Subsequently, we employ the foreach loop to cycle through the elements and display them by utilizing the Console.WriteLine method.

2) Multidimensional Array

In C# programming, a multidimensional array refers to an array comprising multiple arrays as its elements. This data structure allows accessing elements using multiple indices.

Syntax:

It has the following syntax.

Example

data_type array_name[a1][a2]…[an];

Here, a1, a2, …, an define the size of the array.

C# Multidimensional Array Example

Let us take an illustrative example to define the multidimensional array in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {	

        // define the 2-dimensional array

        int[,] mat = {

            {4, 3, 2},

            {6, 1, 5},

            {9, 7, 8}

        };

        // display the 2-dimensional array

        Console.WriteLine("The matrix elements are:");

        for (int i = 0; i < 3; i++)

        {

            for (int j = 0; j < 3; j++)

            {

                Console.Write(mat[i, j] + " ");

            }

            Console.WriteLine();

        }

    }

}

Output:

Output

The matrix elements are:

4 3 2 

6 1 5 

9 7 8

Explanation:

In this instance, we are employing a multidimensional array in C#. Initially, we establish a two-dimensional array with dimensions of 3 rows and 3 columns. Following this, we utilize a nested for loop to traverse through the elements of the array. Finally, we employ the Console.WriteLine method to display the resulting output.

C# Example to display the sum and average of the array Elements

Let's consider an example to calculate the total sum and average of the elements within an array using C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        // Initializaton of an array

        double[] num1 = { 7, 5, 6, 12, 35, 27 };

        double sum1 = 0;

        double count1 = 0;

        double avg1;

        Console.Write("The numbers are: ");

        // Use of the foreach loop to iterate over the value

        foreach (double n in num1)

        {

            Console.Write(n + "  ");

            // calculate the sum of the numbers

            sum1 += n;

            // Count the number of elements

           count1++;

        }

        // Print the sum of the numbers

        Console.WriteLine("\n The sum of numbers = " + sum1);

        // Find the average of the numbers

        avg1 = sum1 / count1;

        Console.WriteLine("The average of the numbers = " + avg1);

    }

}

Output:

Output

The numbers are: 7 5 6 12 35 27  

The sum of numbers = 92

The average of the numbers = 15.3333333333333

Explanation:

In this instance, we illustrate the process of utilizing an array for computing the total and mean of numerical values. Initially, an array is established and labeled as "numbers." Subsequently, we employ a foreach loop to traverse through the elements within the array. Following the iteration, the total and mean of the values are calculated. Lastly, the output is displayed by invoking the Console.WriteLine method.

C# Example to display the Array Element

Here, we will explore a sample to showcase the array element in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int[] num1 = { 7, 5, 6, 12, 35 };

        Console.Write("The numbers are: ");

        foreach (int n in num1)

        {	

            Console.Write(n + "  ");

        }

        Console.Write("\n The numbers are: ");

        for (int i = 0; i < num1.Length; i++)

        {

            Console.Write(num1[i] + "  ");

        }

        Console.WriteLine(); // To move to the next line after output

    }

}

Output:

Output

The numbers are: 7 5 6 12 35  

The numbers are: 7 5 6 12 35

Explanation:

In this code snippet, we are employing a pair of for loops to exhibit the array elements. Initially, we define an array called numbers and assign it with a set of five values. Subsequently, we employ a foreach loop to directly output each element. Ultimately, the Console.WriteLine method is utilized to showcase the result.

Advantages of C# Array:

Several advantages of arrays in C# are as follows:

  • Code Optimization: An array is used to store multiple values in a single variable. This reduces the requirements for multiple individual variables.
  • Random Access: An array element is accessed using an index that represents the position of an array. It allows direct access to the value stored at a specific position.
  • Easy to traverse data: In C#, an array can be traversed very easily with a loop. We can easily access the elements one by one.
  • Easy to manipulate data: In C#, arrays can be manipulated very easily with a loop. We can easily modify the elements one by one.
  • Easy to sort data: In C#, arrays have several built-in function such as sort function.
  • Disadvantages of C# Array:

Several disadvantages of the C# array are as follows:

  • Fixed size: Array sizes are fixed, and cannot be modified once it declared.
  • Wastage of Memory: When we declare a large-sized array, we cannot reduce the memory once it is declared.
  • Lack of flexibility: In C#, array sizes are static, and it cannot be resized dynamically.
  • Conclusion

In C#, the array plays a crucial role for developers in building software applications. It serves as a primary focus during development, allowing for the storage of homogeneous or heterogeneous data elements within a single variable. This helps streamline the process by minimizing the need for numerous separate variables.

C# Array FAQs

1) What is an array in C#?

In C#, an array represents a grouping of identical or diverse data elements within a singular variable. It does not conserve additional memory. Arrays operate by utilizing an index system, where the initial index is 0, and the final element corresponds to size-1.

The Length property of an array indicates the number of elements it contains.

The Length attribute is employed to determine the overall quantity of elements.

Example

using System;

class Program

{

    static void Main()

    {

        int[] my_arr = { 1, 2, 3 };

        Console.WriteLine("The length of an array is " + my_arr.Length);

    }

}

Output:

Output

The length of an array is 3

3) What is a multi-dimensional array in C#?

In C# programming, a multi-dimensional array refers to an array comprising multiple arrays as its elements. It allows accessing elements using multiple indices.

4) Is it possible to modify the size of an array once it has been initialized?

No, in C#, the Array size is constant. Once the size is defined, it cannot be altered for that array.

5) How do we declare and initialize the array?

The declaration and setting up of an array go like this.

Declaration:

Here's the following syntax of array declaration.

Example

int arr [10];

Initialization: o

Here is the syntax for initializing an array:

Example

int my_arr [5] = {1, 2, 3, 4, 5};

Input Required

This code uses input(). Please provide values below: