C#-Arrays

Array in C#

C#-Arrays : C# provides numerous built-in classes to store and manipulate data.One example of such a class is the Array class.

An array is a data structure that is used to store a collection of data. You can think of it as a collection of variables of the same type.


To declare an array, specify its element types with square brackets:

int[ ] myArray;

After creating the array, you can assign values to individual elements by using the index number:

Arrays in C# are zero-indexed meaning the first member has index 0, the second has index 1, and so on.


C#-Arrays & Loops:

It’s occasionally necessary to iterate through the elements of an array, making element assignments based on certain calculations. This can be easily done using loops.

Example :

int[ ] a = new int[10];
for (int k = 0; k < 10; k++) {
  a[k] = k*2;
}

 foreach loop :

The foreach loop provides a shorter and easier way of accessing array elements.

The previous example of accessing the elements could be written using a foreach loop:

Example :

                 int[ ] arr = {11, 35, 62, 555, 989};
int sum = 0; 

foreach (int x in arr) {
  sum += x;
}

Console.WriteLine(sum);
//Outputs 1652
}

The following code uses a foreach loop to calculate the sum of all the elements of an array:

Multidimensional Arrays:

An array can have multiple dimensions. A multidimensional array is declared as follows:

type[, , … ,] arrayName = new type[size1, size2, …, sizeN];

Jagged Arrays:

A jagged array is an array whose elements are arrays. So it is basically an array of arrays.

Example :

                    int[ ][ ] jaggedArr = new int[ ][ ] 
{
  new int[ ] {1,8,2,7,9},
  new int[ ] {2,4,6},
  new int[ ] {33,42}
};

Arrays Properties:

The Length and Rank properties return the number of elements and the number of dimensions of the array, respectively. You can access them using the dot syntax, just like any class members:

Example :


                int[ ] arr = {2, 4, 7};
Console.WriteLine(arr.Length); 
//Outputs 3

Console.WriteLine(arr.Rank); 
//Outputs 1

Array Methods:

There are a number of methods available for arrays.

  • Max: returns the largest value.
  • Min : returns the smallest value.
  • Sum : returns the sum of all elements.

Example :

                     int[ ] arr = { 2, 4, 7, 1};
Console.WriteLine(arr.Max());
//Outputs 7

Console.WriteLine(arr.Min());
//Outputs 1

Console.WriteLine(arr.Sum());
//Outputs 14

Recommended Posts:

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *