Arrays in C#
Arrays in C#
SHARP
INTRODUCTION TO ARRAYS
• An array:
• Is a collection of related values placed in contiguous memory
locations and these values are referenced using a common
array name.
• Simplifies the task of maintaining these values
INTRODUCTION TO ARRAYS
• This means that the first array element has an index number zero
while the last element has an index number n-1, where n stands
for the total number of elements in the array.
• This arrangement of storing values helps in efficient storage of
data, easy sorting of data, and easy tracking of the data length.
INTRODUCTION TO ARRAYS
DECLARING ARRAYS
• Arrays are reference type variables whose creation involves two
steps:
• Declaration:
• An array declaration specifies the type of data that it can hold and
an identifier.
• This identifier is basically an array name and is used with a
subscript to retrieve or set the data value at that location.
• Memory allocation:
• Declaring an array does not allocate memory to the array.
INITIALIZING ARRAYS
• An array can be:
• Created using the new keyword and then initialized. \
• Initialized at the time of declaration itself, in which case the new
keyword is not used.
• Creating and initializing an array with the new keyword involves
specifying the size of an array.
• The number of elements stored in an array depends upon the
specified size.
• The new keyword allocates memory to the array and values can
then be assigned to the array.
USING THE FOREACH LOOP FOR
ARRAYS
• The foreach loop:
• In C# is an extension of the for loop.
• Is used to perform specific actions on large data collections and
can even be used on arrays.
• Reads every element in the specified array.
• Allows you to execute a block of code for each element in the
array.
• Is particularly useful for reference types, such as strings.
TYPES OF ARRAYS
• Based on how arrays store elements, arrays can be categorized into
following two types:
• Single-dimensional Arrays
• Multi-dimensional Arrays
SINGLE-DIMENSIONAL ARRAYS:
• Rectangular Array:
• Is a multi-dimensional array where all the specified dimensions
have constant values.
• Will always have the same number of columns for each row.
MULTI-DIMENSIONAL ARRAYS:
• Rectangular Array:
• There are 3 ways to initialize multidimensional array in C# while
declaration.
• int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
• We can omit the array size.
• int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
• We can omit the new operator also.
• int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
MULTI-DIMENSIONAL ARRAYS:
• Jagged Array:
• Is a multidimensional array where one of the specified dimensions
can have varying sizes.
• Can have unequal number of columns for each row.
INITIALIZING ARRAY
WITH USER INPUT IN
C#