Arrays
Arrays
Array
The index is starting from 0, which stores value. we can also store a
fixed number of values in an array. Array index is to be increased by 1 in
sequence whenever its not reach the array size.
In C# the arrays have fixed length, which is set at the time of their
instantiation and determines the total number of elements. Once the
length of an array is set we cannot change it anymore.
Array Declaration
Syntax:
<Data Type>[ ] <Name_Array>
Here,
<Data Type> : It define the element type of the array.
[ ] : It define the size of the array.
<Name_Array> : It is the Name of array.
Only Declaration of an array doesn’t allocate memory to the array. For
that array must be initialized.
Declaring an Array
int[] myArray;
In this example the variable myArray is the name of the array, which is
of integer type (int[]). This means that we declared an array of integer
numbers. With [] we indicate, that the variable, which we are declaring,
is an array of elements, not a single element.
When we declare an array type variable, it is a reference, which does
not have a value (it points to null). This is because the memory for the
elements is not allocated yet.
Declaring an Array
The figure below shows how a declared array variable looks, when the
memory for elements of the array is not allocated yet:
In the program’s execution stack the variable with the name myArray is
created and its value is set to null (meaning it holds no value).
Array Initialization
With this syntax we use curly brackets instead of the operator new.
Between the brackets we list the initial values of the array, separated by
commas. Their count defines the length of the array.
Declaration and Initialization of an
Array – Example
We access the array elements directly using their indices. Each element
can be accessed through the name of the array and the element’s index
(consecutive number) placed in the brackets. We can access given
elements of the array both for reading and for writing, which means we
can treat elements as variables.
Here is an example for accessing an element of an array:
myArray[index] = 100;
In the example above we set a value of 100 to the element, which is at
position index.
Access the Elements of an Array
int[] myArr = { 1, 2, 3, 4, 5 };
int[] myArr2 = myArr;
myArr[2] = 45;
Console.WriteLine(myArr[2]);
Console.WriteLine(myArr2[2]);
Array class
int[] arr = { 1, 2, 3, 4 };
int a = arr[3];
int b = array[3]; // This will cause a compile-time error
object b = array.GetValue(2);
Array Length
To find out how many elements an array has, use the Length property:
We can iterate through the array using a loop statement. The most
common form of such iteration is by using a for-loop:
myArray[1] = 1;
myArray[5] = 5;
int j = 0;
while (j < myArray.Length)
{
Console.WriteLine(" " + myArray[j]);
j++;
}
Do-while loop :
int k = 0;
do
{
Console.Write(" " + myArray[k]);
k++;
} while (k < myArray.Length);
For-each :
Parameters:
data_type: The type of elements in the collection (e.g., int, string,
etc.).
variable_name: A temporary variable that holds the current
element during each iteration.
collection: The array or collection being iterated over.
The foreach loop uses the in keyword to iterate over each item in the
specified collection. On each iteration, it selects an item from the
collection and stores it in the variable defined. The loop continues until
all elements have been processed.
What Happens When You Use
foreach?
C# automatically does the following:Calls GetEnumerator() on numbers
to get an enumerator.
Calls MoveNext() to move to the next element.
Retrieves the current value using Current.
Repeats steps 2 & 3 until MoveNext() returns false (end of the
collection).
What is an Enumerator?
namespace System.Collections
{
public interface IEnumerator
{
object Current { get; } // Returns the current
element
Non-Index Access: Unlike the for loop, the foreach loop doesn’t
provide an index variable that you can use to reference the position of
the current element in the collection.
Collection Modification: cannot remove or add elements to the
collection while iterating with a foreach loop.
Array Initialization and Default Values
int[] myArray = { 1, 2, 3, 4, 5, 6 };
Console.WriteLine(myArray[6]);
Going Out of Bounds of the Array
int[] intArray;
intArray = new int[5];
intArray[0] = 10;
intArray[1] = 20;
intArray[2] = 30;
intArray[3] = 40;
intArray[5] = 50;
Reading an Array from the Console
int n = int.Parse(Console.ReadLine());
int[] array = new int[n];
int[] myArr = { 10, 20, 30, 40, 20, 90, 80, 100 };
Array.Reverse(myArr);
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine(myArr[i]);
Array.Copy() Method
int[] myArr = { 10, 20, 30, 40, 20, 90, 80, 100 };
int[] myArr2 = new int[10];
Array.Copy(myArr, myArr2, 5);
for (int i = 0; i < myArr2.Length; i++)
Console.WriteLine(myArr2[i]);
Array.Copy() Method
Array.Copy(sourceArray, sourceStartingIndex, destinationArray, destinationStartingIndex,
length);
int[] myArr = { 10, 20, 30, 40, 20, 90, 80, 100 };
int[] myArr2 = new int[10];
Array.Copy(myArr,3, myArr2, 5, 4);
for (int i = 0; i < myArr2.Length; i++)
Console.WriteLine(myArr2[i]);
Example 2
In this array contains only one row for storing the values. All values of this
array are stored contiguously starting from 0 to the array size. For example,
declaring a single-dimensional array of 5 integers :
string[] weekDays;
The multi-dimensional array contains more than one row to store the
values. It is also known as a Rectangular Array in C# because it’s
each row length is same. It can be a 2D-array or 3D-array or more. To
storing and accessing the values of the array, one required the nested
loop. The multi-dimensional array declaration, initialization and
accessing is as follows :
// creates a two-dimensional array of
// four rows and two columns.
int[, ] intarray = new int[4, 2];
Console.WriteLine("Arrays :");
Console.WriteLine();
}
GetLength
};
Console.WriteLine(intarray.GetLength(0));
Console.WriteLine(intarray.GetLength(1));
Rank
Array.Rank is a property of the Array class in C# that returns the number
of dimensions (or "rank") of an array.
int[] oneDimArray = { 1, 2, 3 };
Console.WriteLine(oneDimArray.Rank);
Even though jaggedArray contains arrays inside it, Rank returns 1 because
jagged arrays are arrays of arrays, not multi-dimensional arrays.
Range and Indices
Index index = 2; is equivalent to int index = 2;, but using the Index
struct.
Example
Index fromStart = 2;
Index fromEnd = ^2;
Console.WriteLine(myArr[fromStart]);
Console.WriteLine(myArr[fromEnd]);
Range is defined using two Index values: a start index and an end index
(the end is exclusive)
Range range = start..end;
start is the starting index.
end is the exclusive endpoint of the range.
Example
• ^4 is 4th-to-last element.
• ^1 is the last element.
• This gives you a range of elements starting from the 4th-to-last element
(30) to the 2nd-to-last element (50), excluding the last element.
Example