PLD Topic 7 Arrays
PLD Topic 7 Arrays
DESIGN
C# ARRAYS
ARRAYS
• An array is a collection
of similar types of data.
For example,
• Suppose we need to
record the age of 5
students. Instead of
creating 5 separate
variables, we can simply
create an array:
ARRAY
DECLARATION
HO W MANY
EL EMENTS CAN IT
S TO RE?
To define the
number of
elements that an
array can hold, we
have to allocate
memory for the
array in C#.
ARRAY INITIALIZATION
// create an array
int[] numbers = {1, 2, 3};
Console.ReadLine();
}
}
class Program
{
static void Main(string[] args)
{
// create an array
int[] numbers = { 1, 2, 3 };
Console.ReadLine();
}
}
ITERATING C# class Program
ARRAY USING {
LOOPS static void Main(string[] args)
{
int[] numbers = { 1, 2, 3 };
We can use loops for (int i = 0; i < numbers.Length; i++)
to iterate through {
Console.WriteLine("Element in index " + i + ": " +
each element of an numbers[i]);
}
array.
Console.ReadLine();
}
}
EXAMPLE: USING FOREACH LOOP
class Program
{
static void Main(string[] args) {
int[] numbers = {1, 2, 3};
Console.ReadLine();
}
}
namespace ArrayMinMax
{
class Program
ARRAY O PERATI O NS {
static void Main(string[] args)
U SI NG SYSTEM.LI NQ {
A two-dimensional
array consists of
single-dimensional
arrays as its
elements. It can be
represented as a
table with a specific
number of rows and
columns.
TW O-DIME N SION AL
AR R AY
DE CL AR ATION
TWO-
DIMENS IO NAL
ARRAY
INIT IAL IZ AT IO N
We can
initialize an
array during the
declaration
ACCESS ELEMENTS FROM 2D ARRAY
// a 2D array
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };
//initializing 2D array
int[,] numbers = { { 2, 3 }, { 4, 5 } };
EXAMPLE: 2D
ARRAY // access first element from the first row
Console.WriteLine("Element at index [0, 0] : " + numbers[0, 0]);
int[,] numbers = { { 2, 3 }, { 4, 5 } };
int[,] numbers = { { 2, 3, 9 }, { 4, 5, 9 } };
}
Console.WriteLine();
}
}
}
JAGGED ARRAY
JAG G E D AR R AY
DE CL AR ATIO N
JAGGED ARRAY
DECLARATI O N
We know each
element of a
jagged array is
also an array, we
can set the size of
the individual array.
INITIALIZING JAGGED ARRAY
Here,
• index at the first square
bracket represents the
index of the jagged array
element
• index at the second
square bracket
represents the index of
the element inside each
element of the jagged
array
INITIALIZE WITHOUT SETTING SIZE OF
ARRAY ELEMENTS
INITIALIZE WHILE DECLARING JAGGED
ARRAY
ACCES S ING
EL EMENTS O F A
JAG G ED ARRAY
We can access
the elements of
the jagged
array using the
index number.
class Program
{
We can use
loops to iterate
through each
element of the
jagged array.
JAGGE D AR R AY
W ITH
MULTIDIME N SION A
L AR R AY
Console.WriteLine(jaggedArray[0][0, 1]);
Console.WriteLine(jaggedArray[1][2, 1]);
Console.WriteLine(jaggedArray[2][1, 0]);
Console.ReadLine();
}
}
}