Session 05
Session 05
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
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
y
Example
nl
Consider a program that stores the
O
se
To store the names, the programmer
U
would create 100 variables of type
tre
string.
Creating and managing these 100
en
100 names.
rA
Fo
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
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
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
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
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
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
en
Syntax
C
type[] arrayName = new type[size-value];
h
ec
In the syntax:
pt
specify a variable of type int that stores the size of the array instead of
Fo
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
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
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
}
}
}
© 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
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
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
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
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
Console.WriteLine(students[i]);
}
Fo
}
}
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
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
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
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
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
}
}
}
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
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
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
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
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
classTwo = classOne;
Console.WriteLine("\nStudents of Class II after referencing
Fo
Class I:");
for (int i = 0; i< 3; i++)
{
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
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
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
{
Console.WriteLine();
Console.Write("Enter the Student Name: ");
rA
stdName[i] = Convert.ToString(Console.ReadLine());
for (int y = 0; y < exams; y++)
{
Fo
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
}
}
Fo
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
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
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
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
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
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
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
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
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
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
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
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
In the syntax:
Array: Returns a reference to the created array.
Type: Uses the typeof operator for explicit casting.
Fo
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
must explicitly invoke the method with the appropriate
parameters.
Fo
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
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
en
objArray. Using the GetValue() method, the names of subjects are
displayed in the console window.
C
h
ec
pt
rA
Fo
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
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
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
y
The following figure displays the use of Rank property:
nl
O
se
U
tre
en
C
h
ec
pt
rA
Fo
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