[go: up one dir, main page]

0% found this document useful (0 votes)
15 views69 pages

Arrays

An array is a collection of like-typed variables accessed by a common name, with elements stored contiguously and indexed starting from 0. In C#, arrays have a fixed length determined at instantiation and can be initialized in various ways, including directly assigning values or using the 'new' keyword. The Array class in C# provides methods for creating, searching, and sorting arrays, and all arrays are derived from this class.

Uploaded by

qurbanovelgun090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views69 pages

Arrays

An array is a collection of like-typed variables accessed by a common name, with elements stored contiguously and indexed starting from 0. In C#, arrays have a fixed length determined at instantiation and can be initialized in various ways, including directly assigning values or using the 'new' keyword. The Array class in C# provides methods for creating, searching, and sorting arrays, and all arrays are derived from this class.

Uploaded by

qurbanovelgun090
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Arrays

Array

 An array is a group of like-typed variables that are referred to by a


common name. And each data item is called an element of the array.
The data types of the elements may be any valid data type like char, int,
float, etc. and the elements are stored in a contiguous
location. Length of the array specifies the number of elements present
in the array.
 The array has can contain primitive data types as well as objects of a
class depending on the definition of an array.
 All elements of a given array are of the same type, no matter whether
they are primitive or reference types. This allows us to represent a group
of similar elements as an ordered sequence and work on them as a
whole.
 Arrays can be in different dimensions, but the most used are the one
dimensional and the two-dimensional arrays. One-dimensional arrays
are also called vectors and two-dimensional are also known as matrices.
Array
 The following figure shows how array stores values sequentially:

 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

 As said earlier, an array is a reference type so the new keyword used to


create an instance of the array. We can assign initialize individual array
elements, with the help of the index.
 Syntax:
type [ ] < Name_Array > = new < datatype > [size];
 Here, type specifies the type of data being allocated, size specifies the
number of elements in the array, and Name_Array is the name of an
array variable. And new will allocate memory to an array according to
its size.
Creation of an Array – the Operator
"new"
int[] myArray = new int[6];

 In this example we allocate an array with length of 6 elements of type


int. This means that in the dynamic memory (heap) an area of 6 integer
numbers is allocated and they all are initialized with the value 0:
Array Initialization

 <data_type>[] <arr_name> = new <data_type>[size]; => Defining array with


size, but not assigns values

int[] arr1 = new int[5];

 <data_type>[] <arr_name> = new <data_type>[size]{ array_elements}; =>


Defining array with size and assigning the values at the same time

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

 <data_type>[] <arr_name> = { array_elements}; => The value of the array is


directly initialized without taking its size
int[] intArray3 = { 1, 2, 3, 4, 5 };
Array Initialization and Default Values
 Of course we can set initial values explicitly. We can do this in different
ways. Here is one of them:
int[] myArray = { 1, 2, 3, 4, 5, 6 };
 In this case we create and initialize the elements of the array at the time
of the declaration. On the figure below we see how the array is allocated
in the memory when its values are initialized at the moment of its
declaration:

 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

string[] daysOfWeek ={ "Monday", "Tuesday", "Wednesday", "Thursday",


"Friday", "Saturday", "Sunday" };

 In this case we allocate an array of seven elements of type string. The


type string is a reference type (object) and its values are stored in the
dynamic memory. The variable daysOfWeek is allocated in the stack
memory, and points to a section of the dynamic memory containing the
elements of the array. The type of each of these seven elements is
string, which itself points to a different section of the dynamic memory,
where the real value is stored.
Declaration and Initialization of an
Array – Example
string[] daysOfWeek ={ "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
Initialization of an Array after
Declaration
 Arrays can be initialized after the declaration. It is not necessary to
declare and initialize at the same time using the new keyword.
However, Initializing an Array after the declaration, it must be initialized
with the new keyword. It can’t be initialized by only assigning values.

// Declaration of the array


string[] str1, str2;
// Initialization of array
str1 = new string[5]{
"Element 1", "Element 2", "Element 3", "Element 4", "Element 5};
str2 = new string[5]{
"Element 1", "Element 2", "Element 3", "Element 4", "Element
5"};
Initialization of an Array after
Declaration
 Initialization without giving size is not valid in C#. It will give a compile-
time error.
 Example: Wrong Declaration for initializing an array

// Compile-time error: must give size of an array


int[] intArray = new int[];

// Error : wrong initialization of an array


string[] str1;
str1 = { "Element 1", "Element 2", "Element 3", "Element 4"};
 In C#, when you declare an array without initializing it immediately, you
must use the new keyword when assigning values later.
Boundaries of an Array

 Arrays are by default zero-based, which means the


enumeration of the elements starts from 0. The first element
has the index 0, the second – 1, etc. In an array of N
elements, the last element has the index N-1.
Access to the Elements of an Array

 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

string[] fruits = { "apple", "pear", "banana"};


Console.WriteLine(fruits[2]);
Example

int[] myArr = { 1, 2, 3, 4, 5 };
int[] myArr2 = myArr;
myArr[2] = 45;
Console.WriteLine(myArr[2]);
Console.WriteLine(myArr2[2]);
Array class

 Array class in C# is part of the System namespace and provides


methods for creating, searching, and sorting arrays. The Array class is
not part of the System.Collections namespace, but it is still
considered as a collection because it is based on the IList interface.
The Array class is the base class for language implementations that
support arrays. This means that all arrays in C# (like int[], string[],
double[,], etc.) are actually derived from the Array class.

Array array = new int[] { 2, 5, 8, 4 };


Understanding What's Happening

 new int[] { 2, 5, 8, 4 } creates a normal integer array (int[]).


 Since int[] inherits from System.Array, you can assign it to an Array
variable.
 You can now use Array methods on it, but you lose direct type safety
(e.g., you can't use array[0] directly without casting).
Access to the Elements of an Array
class

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

Array array = new int[] { 2, 5, 8, 4 };

int a = arr[3];
int b = array[3]; // This will cause a compile-time error

Array array = new int[] { 2, 5, 8, 4 };


Console.WriteLine(((int[])array)[0]); // ✅ Works: Outputs 2

object b = array.GetValue(2);
Array Length

 To find out how many elements an array has, use the Length property:

string[] fruits = { "apple", "pear", "banana lemon" };


Console.WriteLine(fruits.Length);
Access to the Elements of an Array

 We can iterate through the array using a loop statement. The most
common form of such iteration is by using a for-loop:

int[] myArray = new int[6];

myArray[1] = 1;
myArray[5] = 5;

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


Console.WriteLine(" " + myArray[i]);
while loop :

int[] myArray = new int[6];


myArray[1] = 1;
myArray[5] = 5;

int j = 0;
while (j < myArray.Length)
{
Console.WriteLine(" " + myArray[j]);
j++;
}
Do-while loop :

int[] myArray = new int[6];


myArray[1] = 1;
myArray[5] = 5;

int k = 0;
do
{
Console.Write(" " + myArray[k]);
k++;
} while (k < myArray.Length);
For-each :

int[] myArray = new int[6];


myArray[1] = 1;
myArray[5] = 5;
Console.WriteLine("");
Console.Write("For-each loop :");

foreach (int i in myArray)


Console.Write(" " + i);
foreach

 foreach in C# is a special type of loop designed to iterate through


collections like arrays, lists, and other enumerable data types. It
simplifies the process of accessing each element in a collection without
the need for manual indexing. This is useful when performing operations
on every element of an array or collection without worrying about the
indexes.
 Syntax of foreach

foreach (data_type variable_name in collection)


{
// Code to execute for each element
}
foreach

 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?

 An enumerator is an object that helps traverse a collection.


 It implements the IEnumerator<T> interface:

namespace System.Collections
{
public interface IEnumerator
{
object Current { get; } // Returns the current
element

bool MoveNext(); // Moves to the next element

void Reset(); // Resets the enumerator (rarely used)


}
}
Example

char[] arr = { 'H', 'e', 'l', 'l', 'o' };

// Using foreach to print


// each character in the array
foreach (char ch in arr)
{
Console.WriteLine(ch);
}
Limitations of the foreach Loop

 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

 Before we can use an element of a given array, it has to be initialized or


to have a default value. In some programming languages there are no
default values and then if we try to access an element, which is not
initialized, this may cause an error. In C# all variables, including the
elements of arrays have a default initial value. This value is either 0 for
the numeral types or its equivalent for the non-primitive types (for
example null for a reference type and false for the bool type).
Example
 Here is an example, where we allocate an array of numbers and then we
change some of them:

int[] students = new int[5];


for (int i = 0; i < students.Length; i++)
Console.WriteLine(students[i]);

int[] myArray = new int[6];


myArray[1] = 1;
myArray[5] = 5;
Example

string[] names = new string[10];


for (int i = 0; i < names.Length; i++)
Console.WriteLine(names[i]);

bool[] letters = new bool[5];


for (int i = 0; i < letters.Length; i++)
Console.WriteLine(letters[i]);
Going Out of Bounds of the Array

 The .NET does an automatic check on each element access attempt,


whether the index is valid or it is out of the range of the array. When we
try to access an invalid (not existing) element in an array, a
System.IndexOutOfRangeException is thrown.

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];

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


{
array[i] = int.Parse(Console.ReadLine());
}
Array.Clear() Method

 This method is used to set a range of elements in an array to the default


value of each element type.

int[] array = new int[] { 2, 5, 8, 4 };


Array.Clear(array);

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


Console.WriteLine(array[i]);
Array.Clear() Method

 (Array array, int index, int length);


 array: It is an array whose elements need to be cleared.
index: It is the starting index of the range of elements to clear.
length: It is the number of elements to clear.

int[] array = new int[] { 2, 5, 8, 4 };


Array.Clear(array, 1,2);

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


Console.WriteLine(array[i]);
Exceptions:

 ArgumentNullException: if array is null


 IndexOutOfRangeException: if the index is less than the lower bound
of the array or the length is less than zero or the sum
of index and length is greater than the size of the array.
Example

int[] myArr = null;


Array.Clear(myArr);

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

Array.Clear(myArr, -1, 2);


for (int i = 0; i < myArr.Length; i++)
Console.WriteLine(myArr[i]);
Array.Reverse() Method

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

 The .Copy() method in C# copies a range of elements from one array to


another array.
Syntax:
Array.Copy(sourceArray, destinationArray, length);
 sourceArray is copied, starting from the first element of the array.
 destinationArray is where the sourceArray is copied to.
 length is specified as an integer and determines how many elements are
copied from the source to the destination array.
Example

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);

 It is also possible to overload this method with two additional


parameters:

 sourceStartingIndex is the index where the source array’s elements are


first copied from.
 destinationStartingIndex is the destination array’s index to which the
elements from the source array are copied to.
Example1

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

int[] myArr = { 100, 20, 70, 40, 0, 90, 80, 3};


int[] myArr2 = new int[myArr.Length];

Array.Copy(myArr, myArr2, myArr.Length);

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


Console.WriteLine(myArr2[i]);
Array.Sort() Method Example

int[] myArr = { 100, 20, 70, 40, 0, 90, 80, 3};


Array.Sort(myArr);
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine(myArr[i]);
Methods

 void methods do not return a value; they modify data in place if


applicable (e.g., Array.Reverse() modifies the original array).
 Non-void methods return a new value or object instead of modifying the
original data (returns a new reversed array without changing the original
one).
Array.CreateInstance() Method

 The C# Array CreateInstance() method is used to create new instance


of an array with a specified type, dimensions, and lengths for each
dimension.
 The array that is created may have one or multiple dimensions,
depending on the length that is given.

int[] arr = new int[5];


Array array = Array.CreateInstance(typeof(int), 5);
Types of Arrays in C#

 One Dimensional Array


 Multi Dimensional Array
 Jagged Array
One Dimensional Array

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 :

int[] arrayint = new int[5];

string[] weekDays;

// allocating memory for days.


weekDays = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu",
"Fri", "Sat" };
Multidimensional Arrays

 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];

//creates an array of three dimensions, 4, 2, and 3


int[,, ] intarray1 = new int[4, 2, 3];
int[,,] arr = new int[4, 2, 3] {
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
{
{ 7, 8, 9 },
{ 10, 11, 12 }
},
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
{
{ 1, 2, 3 },
{ 4, 5, 6 }
},
};
Console.WriteLine("arr[1][0][1] : " + arr[1, 0, 1]);

Console.WriteLine("arr[1][1][2] : " + arr[1, 1, 2]);


Jagged Arrays

 An array whose elements are arrays is known as Jagged arrays it means


“array of arrays“. The jagged array elements may be of different
dimensions and sizes. Below are the examples to show how to declare,
initialize, and access the jagged arrays
int[][] arr = { new int[] { 1, 3, 5, 7, 9 },
new int[] { 2, 4, 6, 8 } };

Console.WriteLine("Arrays :");

// Display the array elements:


for (int i = 0; i < arr.Length; i++)
{
System.Console.Write("Elements[" + i + "] Array: ");

// Printing the elements of array


for (int j = 0; j < arr[i].Length; j++)
{
Console.Write(arr[i][j] + " ");
}

Console.WriteLine();
}
GetLength

 Array.GetLength(Int32) Method is used to find the total number of


elements present in the specified dimension of the Array.
 Return value: The return type of this method is System.Int32. This
method return a 32-bit integer that represents the number of elements
in the specified dimension.
Exception: This method will give IndexOutOfRangeException if the
value of dimension is less than zero or if the value of dimension is equal
to or greater than Rank (Array.Rank is a property of the Array class in C#
that returns the number of dimensions (or "rank") of an array.)
Example

string[] cars = { "Volvo", "BMW", "Ford", "Mazda" };


Console.WriteLine(cars.GetLength(0));

int[,] intarray = new int[4, 2]


{
{2,3 },
{2,3 },
{2,3 },
{2,3 }

};
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);

int[,] twoDimArray = new int[3, 4];


Console.WriteLine(twoDimArray.Rank);

int[,,] threeDimArray = new int[2, 3, 4];


Console.WriteLine(threeDimArray.Rank);

int[][] jaggedArray = new int[3][];


Console.WriteLine(jaggedArray.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

 Range and Indices introduced in C# 8.0. released as part of .NET Core


3.0 and .NET Framework 4.8 they provide a short syntax to represent
or access a single or a range of elements from the given sequence or
collections.
 System.Index: It represents an index in the given sequence or
collection.
 System.Range: It represents a sub-range of the given sequence or
collection.
Index

 Index in C# is a struct introduced in C# 8.0 that represents an index into


a collection. It provides a way to reference elements from both the start
and end of an array using the ^ operator.

int[] myArr = { 3, 4, 66, 6 };


Index index = 2;
int b = myArr[index];
Console.WriteLine(b); // 66

 Index index = 2; is equivalent to int index = 2;, but using the Index
struct.
Example

int[] myArr = { 3, 4, 66, 6 };


Index index = ^2; // Second-to-last element
int b = myArr[index];
Console.WriteLine(b); // 66

Equivalent to: int b = myArr[myArr.Length - 2];


Example

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

Index fromStart = 2;
Index fromEnd = ^2;

Console.WriteLine(myArr[fromStart]);
Console.WriteLine(myArr[fromEnd]);

✔ fromStart = 2; means myArr[2] → 30.


✔ fromEnd = ^2; means myArr[myArr.Length - 2] → 40.
Range

 In C# 8.0 and later, Range is another struct that works in combination


with Index to represent a range of elements in a collection (such as an
array or a list).
 Range defines a start and end position to represent a slice of a
collection.

 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

int[] myArr = { 10, 20, 90, 40, 50 };

Range range = 2..4;


var myRangedArr = myArr[range];

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


{
Console.WriteLine(myRangedArr[i]);
}
Example

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

Range range = ^4..^1;


var myRangedArr = myArr[range];

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


{
Console.WriteLine(myRangedArr[i]);
}

• ^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

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

Range range = 0..^2;


var myRangedArr = myArr[range];

for (int i = 0; i < myRangedArr.Length; i+


+)
{
Console.WriteLine(myRangedArr[i]);
}
Example

int[] myArr = { 10, 20, 30, 40, 50, 60,5,8,6,9,9,4,7,33 };

Range range = 8..^2;


var myRangedArr = myArr[range];

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


{
Console.WriteLine(myRangedArr[i]);
}

You might also like