0% found this document useful (0 votes)
55 views50 pages

Session 05

This document defines and describes arrays. It discusses that arrays are collections of elements of the same data type stored in adjacent memory locations. Arrays simplify storing multiple values of the same type by allowing them to be accessed using an index. Arrays in C# are declared with a type and name, and memory is allocated for the array either at declaration or using the new keyword. Elements in a C# array are accessed using zero-based indexes.

Uploaded by

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

Session 05

This document defines and describes arrays. It discusses that arrays are collections of elements of the same data type stored in adjacent memory locations. Arrays simplify storing multiple values of the same type by allowing them to be accessed using an index. Arrays in C# are declared with a type and name, and memory is allocated for the array either at declaration or using the new keyword. Elements in a C# array are accessed using zero-based indexes.

Uploaded by

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

Click to edit Master title style

y
nl
O
se
U
5

tre
en
C Arrays
h
ec
pt
rA
Fo
Click to edit Master titleObjectives
style

y
Define and describe arrays

nl

O
 List and explain the types of arrays

se
 Explain the Array class

U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 2


Click to editIntroduction to Arrays
Master title style

y
 An array is a collection of elements of a single data type stored in

nl
adjacent memory locations.

O
se
U
tre
en
Example C
h
ec

In a program, an array can be defined to contain 30 elements to


pt

store the scores of 30 students.


rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 3


Purpose
Click to edit Master title style 1-2

y
Example

nl
Consider a program that stores the

O

names of 100 students.

se
 To store the names, the programmer

U
would create 100 variables of type

tre
string.
Creating and managing these 100

en

variables is a tedious task as it results


C
in inefficient memory utilization.
h
 In such situations, the programmer
ec

can create an array for storing the


pt

100 names.
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 4


Purpose
Click to edit Master title style 2-2

y
 An array:

nl
 Is a collection of related values placed in contiguous memory locations and these

O
values are referenced using a common array name.

se
 Simplifies the task of maintaining these values.

U
 An array always stores values of a single data type.

tre
 Each value is referred to as an element.

en
 These elements are accessed using subscripts or index numbers that
determine the position of the element in the array list.
C
C# supports zero-based index values in an array.
h

ec

 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
pt

number of elements in the array.


rA

 This arrangement of storing values helps in efficient storage of data, easy


Fo

sorting of data, and easy tracking of the data length.

© Aptech Ltd. Building Applications Using C# / Session 5 5


Click to edit Master titleDefinition
style

y
 Following figure is an example of the subscripts and elements in

nl
an array:

O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 6


Declaring
Click to edit Master Arrays
title style

y
 Arrays are reference type variables whose creation involves two steps:

nl
 Declaration:

O
– An array declaration specifies the type of data that it can hold and an identifier.

se
– This identifier is basically an array name and is used with a subscript to retrieve or set
the data value at that location.

U
 Memory allocation:

tre
– Declaring an array does not allocate memory to the array.

en
 Following is the syntax for declaring an array:
Syntax
C
h
type[] arrayName;
ec
pt

 In the syntax:
rA

 type: Specifies the data type of the array elements (for example, int and
char).
Fo

 arrayName: Specifies the name of the array.


© Aptech Ltd. Building Applications Using C# / Session 5 7
Initializing
Click to edit Master titleArrays
style 1-7

y
 An array can be:

nl
Created using the new keyword and then initialized.

O

 Initialized at the time of declaration itself, in which case the new keyword

se
is not used.

U
 Creating and initializing an array with the new keyword involves

tre
specifying the size of an array.
The number of elements stored in an array depends upon the

en

specified size.
 C
The new keyword allocates memory to the array and values can
h
then be assigned to the array.
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 8


Initializing
Click to edit Master titleArrays
style 2-7

y
 If the elements are not explicitly assigned, default values are

nl
stored in the array.

O
 The following table lists the default values for some of the widely

se
used data types:

U
Data Types Default Values

tre
int 0

en
float 0.0
C
h
double 0.0
ec

char ‘\0’
pt

string Null
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 9


Initializing
Click to edit Master titleArrays
style 3-7

y
 The following syntax is used to create an array:

nl
Syntax

O
se
arrayName = new type[size-value];

U
The following syntax is used to declare and create an array in the

tre

same statement using the new keyword:

en
Syntax
C
type[] arrayName = new type[size-value];
h
ec

In the syntax:
pt

size-value: Specifies the number of elements in the array. You can


rA

specify a variable of type int that stores the size of the array instead of
Fo

directly specifying a value.

© Aptech Ltd. Building Applications Using C# / Session 5 10


Initializing
Click to edit Master titleArrays
style 4-7

y
 Once an array has been created using the syntax, its elements can

nl
be assigned values using either a subscript or using an iteration

O
construct such as a for loop.

se
 The following syntax is used to create and initialize an array

U
without using the new keyword:

tre
Syntax

en
type[ ] arrayIdentifier = {val1, val2, val3, ..., valN};

In the syntax: C
h

ec

 val1: It is the value of the first element.


 valN: It is the value of the nth element.
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 11


Initializing
Click to edit Master titleArrays
style 5-7

y
 The following code creates an integer array which can have a

nl
maximum of five elements in it:

O
Snippet

se
public int[] number = new int[5];

U
tre
 The following code initializes an array of type string that assigns
names at appropriate index locations:

en
Snippet
C
h
public string[] studNames = new string{“Allan”, “Wilson”,
ec

“James”, “Arnold”};
pt

In the code:
rA


 The string 'Allan' is stored at subscript 0, 'Wilson' at subscript 1, 'James'
at subscript 2, and 'Arnold' at subscript 3.
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 12


Initializing
Click to edit Master titleArrays
style 6-7

y
 The following code stores the string 'Jack' as the name of the fifth

nl
enrolled student:

O
Snippet

se
studNames[4] = “Jack”;

U
 The following code demonstrates another approach for creating

tre
and initializing an array. An array called count is created and is
assigned int values:

en
using System;
class Numbers
{
C
static void Main(string[] args)
h
{
ec

int[] count = new int[10];//array is created


int counter = 0;
pt

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


{
rA

count[i] = counter++; //values are assigned to the elements


Console.WriteLine(“The count value is: “ + count[i]);
//element values are printed
Fo

}
}
}
© Aptech Ltd. Building Applications Using C# / Session 5 13
Initializing
Click to edit Master titleArrays
style 7-7

y
 In the code:

nl
 The class Numbers declares an array variable count of size 10.

O
 An int variable counter is declared and is assigned the value 0.
Using the for loop, every element of the array count is assigned the

se

incremented value of the variable counter.

U
tre
Output

en
The count value is: 0
The count value is: 1
The count value is: 2
C
h
The count value is: 3
ec

The count value is: 4


The count value is: 5
pt

The count value is: 6


rA

The count value is: 7


The count value is: 8
Fo

The count value is: 9

© Aptech Ltd. Building Applications Using C# / Session 5 14


Click to edit MasterTypes of Arrays
title style

y
 Based on how arrays store elements, arrays can be categorized

nl
into following two types:

O
se
U
Arrays

tre
en
C
h
ec
pt
rA

Single-dimensional Arrays Multi-dimensional Arrays


Fo

© Aptech Ltd. Building Applications Using C# / Session 5 15


ClickSingle-dimensional
to edit Master titleArrays
style 1-3

y
 Single-dimensional arrays:

nl
 Elements of a single-dimensional array stored in a single row in allocated

O
memory.
 Declaration/initialization same as standard declaration/initialization of

se
arrays.
Elements indexed from 0 to (n-1), where n is the total number of elements in

U

the array.

tre
Example

en
C
h
ec

Syntax
pt

 The following syntax is used for declaring and initializing a single-


dimensional array:
rA

type[] arrayName; //declaration


Fo

arrayName = new type[length]; // creation

© Aptech Ltd. Building Applications Using C# / Session 5 16


ClickSingle-dimensional
to edit Master titleArrays
style 2-3

y
 In the syntax:

nl
 type: Is a variable type and is followed by square brackets ([]).

O
 arrayName: Is the name of the variable.
length: Specifies the number of elements to be declared in the array.

se

 new: Instantiates the array.

U
The following code initializes a single-dimensional array to store

tre

the name of students:

en
using System;

classSingleDimensionArray
{ C
h
static void Main(string[] args)
ec

{
string[] students = new string[3] {“James”, “Alex”, “Fernando”};
pt

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


{
rA

Console.WriteLine(students[i]);
}
Fo

}
}

© Aptech Ltd. Building Applications Using C# / Session 5 17


ClickSingle-dimensional
to edit Master titleArrays
style 3-3

y
 In the code:

nl
 The class SingleDimensionArray stores the names of the

O
students in the students array.
An integer variable i is declared in the for loop that indicates the

se

total number of students to be displayed.

U
 Using the for loop, the names of the students are displayed as the
output.

tre
Output

en
James
Alex
Fernando C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 18


Click Multi-dimensional
to edit Master titleArrays
style 1-5

y
Example

nl
O
 Consider a scenario where you need to store

se
the roll numbers of 50 students and their
marks in three exams.

U
Using a single-dimensional array, you require

tre

two separate arrays for storing roll numbers
and marks respectively.

en

C
However, using a multi-dimensional array,
you just need one array to store both roll
h
numbers as well as marks.
ec

COLUMNS
pt
rA

ROWS
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 19


Click Multi-dimensional
to edit Master titleArrays
style 2-5

y
 A multi-dimensional array allows you to store combination of

nl
values of a single type in two or more dimensions.

O
 The dimensions of the array are represented as rows and columns
similar to the rows and columns of a Microsoft Excel sheet.

se
 Following are the two types of multi-dimensional arrays:

U
tre
• Is a multi-dimensional array where all the specified dimensions
Rectangular Array have constant values.

en
• Will always have the same number of columns for each row.

C
h
• Is a multidimensional array where one of the specified
ec

Jagged Array dimensions can have varying sizes.


• Can have unequal number of columns for each row.
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 20


Click Multi-dimensional
to edit Master titleArrays
style 3-5

y
 The following is the syntax for creating a rectangular array:

nl
Syntax

O
se
type[,] <arrayName>; //declaration
arrayName = new type[value1 , value2]; //initialization

U
tre
 In the syntax:
type: Is the data type and is followed by [].

en

 arrayName: Is the name of the array.



C
value1: Specifies the number of rows.
value2: Specifies the number of columns.
h

ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 21


Click Multi-dimensional
to edit Master titleArrays
style 4-5

y
 The following code demonstrates the use of rectangular arrays:

nl
Snippet

O
using System;

se
classRectangularArray
{

U
static void Main (string [] args)
{

tre
int[,] dimension = new int [4, 5];
intnumOne = 0;
for (int i=0; i<4; i++)

en
{
for (int j=0; j<5; j++)
{

C
dimension [i, j] = numOne;
numOne++;
h
}
}
ec

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


{
pt

for (int j=0; j<5; j++)


{
rA

Console.Write(dimension [i, j] + “ “);


}
Console.WriteLine();
Fo

}
}
}

© Aptech Ltd. Building Applications Using C# / Session 5 22


Click Multi-dimensional
to edit Master titleArrays
style 5-5

y
 In the code:

nl
 A rectangular array called dimension is created that will have four rows

O
and five columns.
The int variable numOne is initialized to zero.

se

 The code uses nested for loops to store each incremented value of numOne
in the dimension array.

U
 These values are then displayed in the matrix format using again the nested
for loops.

tre
Output

en
0 1 2 3 4
5 6 7 8 9 C
h
10 11 12 13 14
ec

15 16 17 18 19
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 23


FixedMaster
Click to edit and Dynamic Arrays
title style

y
 Arrays can be either:

nl
O
Fixed- Dynamic

se
length arrays
arrays The size of the array is not fixed at the time

U
The number of elements is defined at of the array declaration and can
the time of declaration. dynamically increase at runtime or
whenever required.

tre
For example, an array declared to store the
e-mail addresses of all users who access a

en
particular Web site cannot have a
For example, an array declared for storing predefined length.
days of the week will have exactly seven
In such a case, the length of the array

C
elements.
cannot be specified at the time of
declaration and a dynamic array has to be
used.
h
ec

The number of elements is known and Can add more elements to the array as and
hence, can be defined at the time of when required.
pt

declaration. Therefore, a fixed-length array Created using built-in classes of the .NET
can be used. Framework.
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 24


Click Multi-dimensional
to edit Master titleArrays
style 1-2

y
 The following code demonstrates the use of fixed arrays:

nl
using System;

O
classDaysofWeek
{

se
static void Main(string[] args)
{

U
string[] days = new string[7];
days[0] = "Sunday";

tre
days[1] = "Monday";
days[2] = "Tuesday";

en
days[3] = "Wednesday";
days[4] = "Thursday";

C
days[5] = "Friday";
days[6] = "Saturday";
h
for(int i = 0; i<days.Length; i++)
ec
{
Console.WriteLine(days[i]);
pt

}
}
rA

}
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 25


Click Multi-dimensional
to edit Master titleArrays
style 2-2

y
 In this code:

nl
 A fixed-length array variable, days, of data type string, is declared to

O
store the seven days of the week.
The days from Sunday to Saturday are stored in the index positions 0 to 6 of

se

the array and are displayed on the console using the
Console.WriteLine() method.

U
tre
Output

en
 The following output displays the use of fixed arrays:
C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 26


Array References
Click to edit Master title style 1-2

y
 An array variable can be referenced by another array variable

nl
(referring variable).

O
se
 While referring, the referring array variable refers to the
values of the referenced array variable.

U
tre
 The following code demonstrates the use of array references:
using

en
using System;
classStudentReferences
{
public static void Main()
{ C
h
string[] classOne = { "Allan", "Chris", "Monica" };
string[] classTwo = { "Katie", "Niel", "Mark"};
ec

Console.WriteLine("Students of Class I:\tStudents of Class II");


for (int i = 0; i< 3; i++)
{
pt

Console.WriteLine(classOne[i] + "\t\t\t" + classTwo[i]);


}
rA

classTwo = classOne;
Console.WriteLine("\nStudents of Class II after referencing
Fo

Class I:");
for (int i = 0; i< 3; i++)
{

© Aptech Ltd. Building Applications Using C# / Session 5 27


Array References
Click to edit Master title style 2-2

y
Console.WriteLine(classTwo[i] + " ");

nl
}
Console.WriteLine();

O
classTwo[2] = "Mike";
Console.WriteLine("Students of Class I after changing the third
student in Class II:");

se
for (int i = 0; i< 3; i++)
{

U
Console.WriteLine(classOne[i] + " ");
}
}

tre
}

en
 In the code:
 classOneis assigned to classTwo; therefore, both the arrays
C
reference the same set of values.
Consequently, when the third array element of classTwo is
h

changed from ‘Monica’ to 'Mike', an identical change is seen in the
ec

third element of classOne.


pt

 The following figure displays the use of array references:


rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 28


Click to editRectangular
Master titleArrays
style 1-4

y
 A rectangular array is a two-dimensional array where each row

nl
has an equal number of columns.

O
se
 The following syntax displays the marks stored in a rectangular
array:

U
Syntax

tre
type [,]<variableName>;

en
variableName = new type[value1 , value2];

 In the syntax: C
h
 type: Specifies the data type of the array elements.
ec

 [,]: Specifies that the array is a two-dimensional array.


 variableName: Specifies the name of the two-dimensional array.
pt

 new: Is the operator used to instantiate the array.


rA

 value1: Specifies the number of rows in the two-dimensional array.


 value2: Specifies the number of columns in the two-dimensional array.
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 29


Click to editRectangular
Master titleArrays
style 2-4

y
 The following code allows the user to specify the number of

nl
students, their names, the number of exams, and the marks

O
scored by each student in each exam.
All these marks are stored in a rectangular array.

se

Snippet

U
using System;

tre
class StudentsScore
{
void StudentDetails()

en
{
Console.Write("Enter the number of Students: ");
int noOfStds = Convert.ToInt32(Console.ReadLine());

C
Console.Write("Enter the number of Exams: ");
int exams = Convert.ToInt32(Console.ReadLine());
string[] stdName = new string[noOfStds];
h
string[,] details = new string[noOfStds, exams];
ec

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


pt

{
Console.WriteLine();
Console.Write("Enter the Student Name: ");
rA

stdName[i] = Convert.ToString(Console.ReadLine());
for (int y = 0; y < exams; y++)
{
Fo

Console.Write("Enter Score in Exam " + (y + 1) + ": ");


details[i, y] = Convert.ToString(Console.ReadLine());

© Aptech Ltd. Building Applications Using C# / Session 5 30


Click to editRectangular
Master titleArrays
style 3-4

y
nl
Snippet

O
}
}

se
Console.WriteLine();
Console.WriteLine("Student Exam Details");
Console.WriteLine("--------------------");

U
Console.WriteLine();
Console.WriteLine("Student\t\tMarks");

tre
Console.WriteLine("-----\t\t-------" );
for (int i = 0; i<stdName.Length; i++)
{

en
Console.WriteLine(stdName[i]);
for (int j = 0; j < exams; j++)
{
} C
Console.WriteLine("\t\t" + details[i, j]);
Console.WriteLine();
h
}
ec
}
static void Main()
{
pt

StudentsScore objStudentsScore = new StudentsScore();


objStudentsScore.StudentDetails();
rA

}
}
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 31


Click to editRectangular
Master titleArrays
style 4-4

y
 In the code:

nl
 The StudentsScore class allows the user to enter the number of students in

O
the class, the names of the students, the number of exams conducted, and the
marks scored by each student in each exam.

se
 The class declares a method StudentDetails, which accepts the student and

U
the exam details.

tre
 The variable noOfStds stores the number of students whose details are to be
stored.

en
 The variable exams stores the number of exams the students have appeared in.
The array stdName stores the names of the students.
C
h
 The dimensions of the rectangular array details are defined by the variables
noOfStds and exams.
ec
pt

 This array stores the marks scored by students in the various exams. A nested for
loop is used for displaying the student details.
rA

 In the Main method, an object is created of the class StudentsScore and the
method StudentDetails is called through this object.
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 32


Jagged
Click to edit Master titleArrays
style 1-3

y
 A jagged array:

nl
Is a multi-dimensional array and is referred to as an array of arrays.

O
 Consists of multiple arrays where the number of elements within each
array can be different. Thus, rows of jagged arrays can have different

se
number of columns.
 Optimizes the memory utilization and performance because navigating

U
and accessing elements in a jagged array is quicker as compared to
other multi-dimensional arrays.

tre
Example

en
 Consider a class of 500 students where each student has opted for a
different number of subjects.

for each student varies.C
Here, you can create a jagged array because the number of subjects
h
ec
 The following figure displays the representation of jagged arrays:
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 33


Jagged
Click to edit Master titleArrays
style 2-3

y
 The following code demonstrates the use of jagged arrays to

nl
store the names of companies:

O
using System;

se
classJaggedArray
{

U
static void Main (string[] args)
{
string[][] companies = new string[3][];

tre
companies[0] = new string[] {“Intel”, “AMD”};
companies[1] = new string[] {“IBM”, “Microsoft”, “Sun”};
companies[2] = new string[] {“HP”, “Canon”, “Lexmark”,

en
“Epson”};
for (int i=0; i<companies.GetLength (0); i++)
{
“:\t”);
C
Console.Write(“List of companies in group “ + (i+1) +
for (int j=0; j<companies[i].GetLength (0); j++)
h
{
ec
Console.Write(companies [i][j] + “ “);
}
Console.WriteLine();
pt

}
}
rA

}
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 34


Jagged
Click to edit Master titleArrays
style 3-3

y
 In the code:

nl
 A jagged array called companies is created that has three rows.

O
 The values 'Intel' and 'AMD' are stored in two separate columns of
the first row.

se
 Similarly, the values 'IBM', 'Microsoft‘, and 'Sun' are stored in
three separate columns of the second row.

U
 Finally, the values 'HP', 'Canon', 'Lexmark', and 'Epson' are
stored in four separate columns of the third row.

tre
en
Output

C
List of companies in group 1: Intel AMD
h
List of companies in group 2: IBM Microsoft Sun
ec

List of companies in group 3: HP Canon Lexmark Epson


pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 35


the foreach
Using Click Loop title
to edit Master for Arrays
style 1-3

y
 The foreach loop:

nl
 In C# is an extension of the for loop.

O
 Is used to perform specific actions on large data collections and can
even be used on arrays.

se
 Reads every element in the specified array.

U
 Allows you to execute a block of code for each element in the array.
 Is particularly useful for reference types, such as strings.

tre
 The following is the syntax for the foreach loop:

en
Syntax
C
foreach(type<identifier> in <list>)
h
{
ec
// statements
}
pt
rA

 In the code:
 type: Is the variable type.
Fo

 identifier: Is the variable name.


 list: Is the array variable name.
© Aptech Ltd. Building Applications Using C# / Session 5 36
the foreach
Using Click Loop title
to edit Master for Arrays
style 2-3

y
 The following code displays the name and the leave grant

nl
status of each student using the foreach loop:

O
Snippet

se
using System;

U
class Students

tre
{
static void Main(string[] args)
{

en
string[] studentNames = new string[3] { “Ashley”, “Joe”,
“Mikel”};

C
foreach (string studName in studentNames)
{
h
Console.WriteLine(“Congratulations!! “ + studName + “ you
have been granted an extra leave”);
ec

}
}
pt

}
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 37


the foreach
Using Click Loop title
to edit Master for Arrays
style 3-3

y
 In the code:

nl
 The Students class initializes an array variable called studentNames.

O
 The array variable studentNames stores the names of the students.
In the foreach loop, a string variable studName refers to every

se

element stored in the array variable studentNames.
For each element stored in the studentNames array, the foreach

U

loop displays the name of the student and grants a day’s leave extra for
each student.

tre
en
Output
C
Congratulations!! Ashley you have been granted an extra leave
h
Congratulations!! Joe you have been granted an extra leave
Congratulations!! Mikel you have been granted an extra leave
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 38


Click to edit Master titleArray
styleClass

y
 The Array class:

nl
 Is a built-in class in the System namespace and is the base class for all

O
arrays in C#.
 Provides methods for various tasks such as creating, searching, copying, and

se
sorting arrays.

U
Example

tre
 Consider a code that stores the marks of a particular subject for 100

en
students.
 The programmer wants to sort the marks, and to do this, he/she has to
 C
manually write the code to perform sorting.
This can be tedious and result in increased lines of code.
h
 However, if the array is declared as an object of the Array class, the built-in
ec

methods of the Array class can be used to sort the array.


pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 39


Properties
Click to andtitle
edit Master Methods
style 1-2
The Array class consists of system-defined properties and

y

nl
methods that are used to create and manipulate arrays in C#.

O
 The properties are also referred to as system array class properties.
 Properties:

se
— The properties of the Array class allow you to modify the elements declared in
the array.

U
— The following table displays the properties of the Array class:

tre
Properties Descriptions
Returns a boolean value, which indicates whether the array has a fixed size or not. The

en
IsFixedSize
default value is true.
Returns a boolean value, which indicates whether an array is read-only or not. The

C
IsReadOnly
default value is false.
h
IsSynchronized Returns a boolean value, which indicates whether an array can function well while
ec
being executed by multiple threads together. The default value is false.
Length Returns a 32-bit integer value that denotes the total number of elements in an array.
pt

LongLength Returns a 64-bit integer value that denotes the total number of elements in an array.
rA

Rank Returns an integer value that denotes the rank, which is the number of dimensions in
an array.
Fo

SyncRoot Returns an object which is used to synchronize access to the array.

© Aptech Ltd. Building Applications Using C# / Session 5 40


Properties
Click to andtitle
edit Master Methods
style 2-2

y
 Methods:

nl
— The Array class allows you to clear, copy, search, and sort the elements

O
declared in the array.
— The following table displays the most commonly used methods in the

se
Array class:
Methods Descriptions

U
Clear Deletes all elements within the array and sets the size of the array to 0.

tre
CopyTo Copies all elements of the current single-dimensional array to another
single-dimensional array starting from the specified index position.

en
GetLength Returns number of elements in an array.
GetLowerBound Returns the lower bound of an array.
C
GetUpperBound Returns the upper bound of an array.
h
ec

Initialize Initializes each element of the array by calling the default constructor of
the Array class.
pt

Sort Sorts the elements in the single-dimensional array.


rA

SetValue Sets the specified value at the specified index position in the array.
GetValue Gets the specified value from the specified index position in the array.
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 41


Click toUsing the Array
edit Master Class 1-5
title style
The Array class allows you to create arrays using the

y

CreateInstance() method.

nl
O
 This method can be used with different parameters to create single-

se
dimensional and multi-dimensional arrays.

U
 For creating an array using this class, you need to invoke the
CreateInstance() method that is accessed by specifying the class

tre
name because the method is declared as static.

en
 The following is the syntax for signature of the CreateInstance()
C
method used for creating a single-dimensional array:
h
Syntax
ec

public static Array CreateInstance(Type elementType, int length)


pt
rA

 In the syntax:
 Array: Returns a reference to the created array.
Type: Uses the typeof operator for explicit casting.
Fo

 elementType: Is the resultant data type in casting.


 Length: Specifies the length of the array.

© Aptech Ltd. Building Applications Using C# / Session 5 42


Click toUsing the Array
edit Master Class 2-5
title style
The following is the syntax for signature of the

y

nl
CreateInstance() method used for creating a
multi-dimensional array.

O
se
Syntax

U
public static Array CreateInstance(Type elementType, int length1,
int length2)

tre
en
 In the syntax:
length1: Specifies the row length.
C

 length2: Specifies the column length.


h
ec

 These syntax determine how the method is declared in the


Array class.
pt

To create single-dimensional and multi-dimensional arrays, you


rA


must explicitly invoke the method with the appropriate
parameters.
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 43


Click toUsing the Array
edit Master Class 3-5
title style
The following code creates an array of length 5 using the Array

y

nl
class and stores the different subject names:

O
Snippet

se
using System;

U
class Subjects
{

tre
static void Main(string [] args)
{
Array objArray = Array.CreateInstance(typeof (string), 5);

en
objArray.SetValue(“Marketing”, 0);
objArray.SetValue(“Finance”, 1);

C
objArray.SetValue(“Human Resources”, 2);
objArray.SetValue(“Information Technology”, 3);
objArray.SetValue(“Business Administration”, 4);
h
for (int i = 0; i<= objArray.GetUpperBound(0); i++)
{
ec

Console.WriteLine(objArray.GetValue(i));
}
pt

}
}
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 44


Click toUsing the Array
edit Master Class 4-5
title style
In the code:

y

nl
 The Subjects class creates an object of the Array class called
objArray.

O
se
 The CreateInstance() method creates a single-dimensional array
and returns a reference of the Array class.

U
Here, the parameter of the method specifies the data type of the array.

tre

The SetValue() method assigns the names of subjects in the

en

objArray. Using the GetValue() method, the names of subjects are
displayed in the console window.
C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 45


Click toUsing the Array
edit Master Class 5-5
title style
For manipulating an array, the Array class uses the following

y

nl
four interfaces:

O
se
ICloneable ICollection IList IEnumerable

U
•The Icloneable •The Icollection •The IList interface •The Ienumerable
interface belongs to the interface belongs to the belongs to the interface belongs to the

tre
System namespace and System.Collections System.Collections System.Collections
contains the Clone() namespace and contains namespace and allows you namespace.
method that allows you to properties that allow you to to modify the elements •This interface returns an
count the number of

en
create an exact copy of the defined in the array. enumerator that can be
current object of the class. elements, check whether •The interface defines three used with the foreach
the elements are properties,
synchronized and if they loop to iterate through a

C
are not, then synchronize
IsFixedSize, collection of elements such
IsReadOnly, and Item. as an array.
the elements in the
collection.
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 46


Rank oftitle
Click to edit Master an style
Array 1-3
Rank is a read-only property that specifies the number of

y

nl
dimensions of an array.

O
Example A three-dimensional array has rank three.

se
U
 The following code demonstrates the use of the Rank property:

tre
Snippet

en
using System;

C
class Employee
{
public static void Main()
h
{
ec
Array objEmployeeDetails = Array.CreateInstance(typeof(string), 2,3);
objEmployeeDetails.SetValue("141", 0, 0);
objEmployeeDetails.SetValue("147", 0, 1);
pt

objEmployeeDetails.SetValue("154", 0, 2);
objEmployeeDetails.SetValue("Joan Fuller", 1, 0);
rA

objEmployeeDetails.SetValue("Barbara Boxen", 1, 1);


objEmployeeDetails.SetValue("Paul Smith", 1, 2);
Console.WriteLine("Rank : " + objEmployeeDetails.Rank);
Console.WriteLine("Employee ID \tName");
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 47


Rank oftitle
Click to edit Master an style
Array 2-3

y
for (int i = 0; i< 1 ; i++)
{

nl
for (int j = 0; j < 3; j++)
{

O
Console.Write(objEmployeeDetails.GetValue(i, j) + "\t\t
");

se
Console.WriteLine(objEmployeeDetails.GetValue(i+1, j));
}
}

U
}
}

tre
 In the code:

en
 The CreateInstance() method creates a two-dimensional array of the specified
type and dimension lengths.

C
Since this array has two dimensions, its rank will be 2.
An instance of this class objEmployeeDetails is created and two sets of values
h

are then inserted in the object objEmployeeDetails using the method
ec

SetValue().
 The values stored in the array are employee ID and the name of the employee. The
pt

Rank property retrieves the rank of the array which is displayed by the
WriteLine() method.
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 48


Rank oftitle
Click to edit Master an style
Array 3-3

y
 The following figure displays the use of Rank property:

nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 49


Click to edit Master title Summary
style

y
 Arrays are a collection of values of the same data type.

nl
 C# supports zero-based index feature.

O
 There are two types of arrays in C#: Single-dimensional and Multi-dimensional
arrays.

se
 A single-dimensional array stores values in a single row whereas a multi-
dimensional array stores values in a combination of rows and columns.

U
 Multi-dimensional arrays can be further classified into rectangular and jagged
arrays.

tre
 The Array class defined in the System namespace enables to create arrays easily.
The Array class contains the CreateInstance() method, which allows you to

en

create single and multi-dimensional arrays.

C
h
ec
pt
rA
Fo

© Aptech Ltd. Building Applications Using C# / Session 5 50

You might also like