Module 2 Arrays
Module 2 Arrays
Unit 2
Arrays
Introduction
Before we formally define an array, let’s consider the following problems.
We want to write a C# program that reads five numbers, finds their sum, and
prints the numbers in reverse order.
Learning Objectives
At the end of the session, you will be able to:
a. declare and create arrays
b. initialize arrays
c. index array elements correctly
d. access array values
e. sort array elements in ascending and descending order
f. search for specific element in an array
1
Unit 2: ARRAYS
Presentation of Contents
One-Dimensional Array
A one-dimensional array is an array in which the elements are
arranged in a list form.
2
Unit 2: ARRAYS
The general syntax to instantiate an array object is:
You can combine the statements in Lines 1 and 2 into one statement
as follows:
The statement:
arrayName[indexExp]
3
Unit 2: ARRAYS
Consider the following statement:
list[5] = 34;
stores 34 into list[5], which is the sixth element of the array list as shown
below.
list[3] = 63;
is equivalent to the assignment statements:
i = 3;
list[i] = 63;
list[2 * i - 3] = 58;
4
Unit 2: ARRAYS
The first statement stores 10 into list[3], the second statement stores 35
into list[6],
and the third statement adds the contents of list[3] and list[6] and stores the
result into list[5].
The statement in Line 2 asks the user to enter the size of the array when
the program executes. The statement in Line 3 inputs the size of the array into
arraySize. During program execution, the system uses the value of the
variable arraySize to instantiate the object list. For example, if the value of
arraySize is 15, list is an array of size 15.
The initializer list contains values, called initial values, that are placed
between braces and separated by commas. Here, sales[0] = 12.25, sales[1] =
32.50, sales[2] = 16.90, sales[3] = 23.00, and sales[4]= 45.68.
5
Unit 2: ARRAYS
• If an array is declared and initialized simultaneously, we do not use the
operator new to instantiate the array object.
This statement creates the array list of six elements and initializes the
elements using the values given. Here, list.Length is 6.
These statements store 5, 10, 15, and 20, respectively, in the first four
elements of numList. Even though we put data into only the first four
elements, the value of numList.Length is 10, the total number of array
elements.
6
Unit 2: ARRAYS
Processing One-Dimensional Arrays
The following for loop steps through each element of the array list,
starting at the first
element of list:
If processing list requires inputting data into list, the statement in Line 2
takes the form of an input statement, such as in the following code. The
following statements read 100 numbers from the keyboard and store the
numbers into list:
The following example shows how loops are used to process arrays. The
following declaration is used throughout this example:
The first statement creates the array sales of 10 elements, with each
element of type double. The meaning of the other statements is clear. Also,
notice that the value of sales.Length is 10.
7
Unit 2: ARRAYS
Loops can be used to process arrays in several ways:
2. Reading data into an array: The following loop inputs data into the
array sales. For simplicity, we assume that the data is entered at the
keyboard one number per line.
3. Printing an array: The following loop outputs the elements of array sales.
For simplicity, we assume that the output goes to the screen.
4. Finding the sum and average of an array: Because the array sales, as
its name implies, represents certain sales data, it may be desirable to
find the total sale and average sale amounts. The following C# code
finds the sum of the elements of the array sales (total sales) and the
average sale amount:
double sum = 0;
for (int index = 0; index < sales.Length; index++)
sum = sum + sales[index];
if (sales.Length != 0)
average = sum / sales.Length;
else
average = 0.0;
8
Unit 2: ARRAYS
Using For Loop – One Dimensional Array
class OnedimensionalLoop
{
public static void main(String args[])
{
{
Console.WriteLine("a["+i+"]:"+a[i]);
}
}
}
Output:
One dimensional array elements are :
a[0]:10
a[1]:20
a[2]:30
a[3]:40
a[4]:50
9
Unit 2: ARRAYS
Using String
1. We declared one-dimensional string array with the elements strings.
2. To print strings from the string array. for i=0 to i<length of the string print string
which is at the index str[i].
class OneDimensionString
{
public static void main(String[] args)
{
//declare and initialize one dimension array
String[] str = new String[]{"one", "two", "three", "four"};
Console.WriteLine("These are elements of one Dimensional array.");
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine(str[i] + " ");
}
}
}
Output:
These are elements of one Dimensional array.
one
two
three
four
Algorithm
- An algorithm is an effective method for solving a problem using a finite
sequence of instructions. Algorithms are used for calculation, data
processing, and many other fields.
- An algorithm is a finite set of well-defined instructions for accomplishing some
tasks which, given an initial state, will result in a corresponding recognizable
end-state.
Classifications of Algorithms
1. Linear Search Algorithm
- Linear search or sequential search is a method for finding a particular value in
a list, that consists in checking every one of its elements, one at a time and in
sequence, until the desired one is found.
- The simplest way to find an object in an array is to start at the beginning and
inspect each element, one after the other, until the object is found.
10
Unit 2: ARRAYS
2. Bubble Sort Algorithm
- Bubble sort is a simple sorting algorithm. It works by repeatedly stepping
through the list to be sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order. The pass through the list is
repeated until no swaps are needed, which indicates that the list is sorted.
11
Unit 2: ARRAYS
Linear Search in C#
Linear search is used to search a key element from multiple elements. Linear search
is less used today because it is slower than binary search and hashing.
Algorithm:
12
Unit 2: ARRAYS
Linear Search in C# (Another way)
You can also use a method where array is not predefined. Here, user has to put the
elements as input and select one element to check its location.
class LinearSearchExample2
{
public static void main(String args[])
{
int c, n, search;
int[] array;
13
Unit 2: ARRAYS
C# program to sort a one-dimensional array in ascending order
Here, we are implementing a C# program to sort an array (one-dimensional array) in
ascending order? We are reading array elements, arranging them in ascending
order and printing the sorted array.
Given an array and we have to sort its elements in ascending order and print the
sorted array using C# program.
Example:
Input:
Array (elements will be read in program): 25 54 36 12 48 88 78 95 54 55
Output:
Sorted List in Ascending Order :
12 25 36 48 54 54 55 78 88 95
// enter elements.
Console.WriteLine("Enter " +n+ " Numbers : ");
for(i=0; i<n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
14
Unit 2: ARRAYS
Output
15
Unit 2: ARRAYS
for (int i = 0; i < n; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
Console.Write("Descending Order:");
for (int i = 0; i < n - 1; i++)
{
Console.Write(a[i] + ",");
}
Console.Write(a[n - 1]);
}
}
Output:
Enter no. of elements you want in array:5
Enter all the elements:
2
3
5
1
4
Descending Order:5,4,3,2,1
Binary search is a divide and conquer algorithm. Like all divide and conquer
algorithms, Binary Search first divides a large array into smaller sub-arrays and then
operate the sub-arrays. But instead of operating on both sub-arrays, it discards one
sub-array and continue on the second sub-array. This decision of discarding one
sub-array is made in just one comparison.
So Binary Search basically reduces the search space to half at each step.
By search space we mean sub-array of given array where the target value is located
(if present in the array). Initially, the search space is the entire array and binary
search redefine the search space at every step of the algorithm by using the
property of the array that is sorted. It does so by comparing the mid value in the
16
Unit 2: ARRAYS
search space to the target value. If the target value matches the middle element, its
position in the array is returned else it discards half of the search space based on the
comparison result.
Let us track the search space by using two index –start and end. Initially
start = 0, and end = n-1. At each step, we find the mid value in the search space
and compares it with target value. There three cases possible
17
Unit 2: ARRAYS
Target = 7
2 3
5 7
Mid
Since 5(Mid)<7(target),
We discard the Left half and go to Right
New Low = Mid + 1
18
Unit 2: ARRAYS
int mid = (left + right) / 2;
if (index != -1) {
Console.WriteLine("Element found at index " + index);
} else {
Console.WriteLine("Element not found in the array");
}
}
}
19
Unit 2: ARRAYS
Topic 2: Multi-Dimensional Arrays
Time Allotment: 4 hours
Learning Objectives
20
Unit 2: ARRAYS
Presentation of Contents
Examples:
21
Unit 2: ARRAYS
Example:
class TwoDim {
public static void main(String[] args)
{
Output:
arr[0,0] = 1
Syntax:
data_type[ , ] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};
For example: int[ , ] arr = {{1, 2}, {3, 4}};
Example:
class TwoDim {
public static void main(String[] args)
{
int[ , ] arr = { { 1, 2 }, { 3, 4 } };
Output:
arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4
22
Unit 2: ARRAYS
Accessing Elements of Two-Dimensional Arrays
Elements in two-dimensional arrays are commonly referred by x[i,j] where ‘i’ is
the row number and ‘j’ is the column number.
Syntax:
x[row_index, column_index]
For example:
int[ , ] arr = new int[10, 20];
arr[0, 0] = 1;
The above example represents the element present in first row and first
column.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for
row_index 2, actual row number is 2+1 = 3.
Example:
class TwoDim {
public static void main(String[] args)
{
int[ , ] arr = { { 1, 2 }, { 3, 4 } };
Output:
arr[0, 0] = 1
23
Unit 2: ARRAYS
Print 2D array in tabular format:
To output all the elements of a Two-Dimensional array, use nested for loops.
For this two for loops are required, One to traverse the rows and another to
traverse columns.
Example:
class TwoDim {
public static void main(String[] args)
{
int[ , ] arr = { { 1, 2 }, { 3, 4 } };
Output:
12
34
Initialization – Syntax:
array_name[array_index][row_index][column_index] = value;
For example: arr[0, 0, 0] = 1;
Example:
class ThreeDim {
public static void main(String[] args)
{
int[ , , ] arr = new int[10, 20, 30];
arr[0, 0, 0] = 1;
24
Unit 2: ARRAYS
}
}
Output:
arr[0, 0, 0] = 1
For example: int[ , , ] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}} };
Example:
class ThreeDim {
public static void main(String[] args)
{
int[ , , ] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Output:
arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8
25
Unit 2: ARRAYS
Accessing Elements of Three-Dimensional Arrays
Elements in three-dimensional arrays are commonly referred by x[i, j, k] where
‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number.
Syntax:
x[array_index, row_index, column_index]
For example:
int[ , , ] arr = new int[10, 20, 30];
arr[0, 0, 0] = 1;
The above example represents the element present in the first row and first
column of the first array in the declared 3D array.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for
row_index 2, actual row number is 2+1 = 3.
Example:
class ThreeDim {
public static void main(String[] args)
{
int[ , , ] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
Output:
arr[0][0][0] = 1
26
Unit 2: ARRAYS
Representation of 3D array in Tabular Format: A three – dimensional array can
be seen as a tables of arrays with ‘x’ rows and ‘y’ columns where the row
number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A
three – dimensional array with 3 array containing 3 rows and 3 columns is
shown below:
27
Unit 2: ARRAYS
Console.WriteLine();
}
Console.WriteLine ();
}
}
}
Output:
12
34
56
78
Example:
Given Array:
[[5, 12, 17, 21, 23]
[1, 2, 4, 6, 8]
[12, 14, 18, 19, 27]
[3, 7, 9, 15, 25]]
Sorted Array:
[[1, 2, 3, 4, 5]
[6, 7, 8, 9, 12]
[12, 14, 15, 17, 18]
[19, 21, 23, 25, 27]]
Approach:
▪ Each row is sorted, we will take advantage of this.
▪ Since each row is sorted which means the first column for each row will
have the minimum element among their respective rows, which also
means that minimum element in the entire matrix will be from the first
column. So, we will pick that smallest element and replace it with the first
element in the matrix.
▪ Now we have successfully placed the right element at the first position in
the array. Now we will restore the original property of the array which is
each row is sorted. So, we will shift the swapped element (earlier with the
first position of the matrix) till it finds its right place in the array.
28
Unit 2: ARRAYS
▪ Now we need to find the second most minimum element for the second
position which will be among elements at the second column in the first
row and first column in the rest of the rows. Once found, swap it and
again reorder to restore the original property.
▪ Repeat this process until the entire array is sorted.
29
Unit 2: ARRAYS
See the example below for more understanding
30
Unit 2: ARRAYS
Sample Program:
public class Sort2D {
31
Unit 2: ARRAYS
}
}
}
}
Output:
32
Unit 2: ARRAYS
Row wise Sorting in 2D array
// C# code to sort 2D matrix row-wise
class 2DRowWise
{
static int sortRowWise(int[,] m)
{
// loop for rows of matrix
for (int i = 0; i < m.GetLength(0); i++)
{
// loop for column of matrix
for (int j = 0; j < m.GetLength(1); j++)
{
// loop for comparison and swapping
for (int k = 0; k < m.GetLength(1) - j - 1; k++)
{
if (m[i, k] > m[i, k + 1])
{
// swapping of elements
int t = m[i, k];
m[i, k] = m[i, k + 1];
m[i, k + 1] = t;
}
}
}
}
// printing the sorted matrix
for (int i = 0; i < m.GetLength(0); i++)
{
for (int j = 0; j < m.GetLength(1); j++)
Console.Write(m[i, j] + " ");
Console.WriteLine();
}
return 0; }
public static void Main(String []args)
{
int [,]m = {{ 9, 8, 7, 1 },
{ 7, 3, 0, 2 },
{ 9, 5, 3, 2 },
{ 6, 3, 1, 2 }};
sortRowWise(m);
}}
33
Unit 2: ARRAYS
Output:
1789
0237
2359
1236
Examples:
1) Perform binary search on the middle column till only two elements are left
or till the middle element of some row in the search is the required element
'x'. This search is done to skip the rows that are not required
2) The two left elements must be adjacent. Consider the rows of two
elements and do the following:
a) check whether the element 'x' equals to the middle element of any one
of the 2 rows
34
Unit 2: ARRAYS
b) otherwise according to the value of the element 'x' check whether it is
present in the 1st half of 1st row, 2nd half of 1st row,1st half of 2nd row or
2nd half of 2nd row.
Note: This approach works for the matrix n x m where 2 <= n. The algorithm
can be modified for matrix 1 x m, we just need to check whether 2nd
row exists or not.
Example:
Consider: | 1 2 3 4|
x = 3, mat = | 5 6 7 8| Middle column:
| 9 10 11 12| = {2, 6, 10, 14}
|13 14 15 16| perform binary search on them since, x < 6,
discard the last 2 rows as 'x' will not lie in them
(sorted matrix)
// C# implementation to search
// an element in a sorted matrix
class Search
{
// This function does Binary search for x in i-th row.
// It does the search from mat[i,j_low] to mat[i,j_high]
static void binarySearch(int[,] mat, int i, int j_low, int j_high, int x)
{
while (j_low <= j_high)
{
int j_mid = (j_low + j_high) / 2;
// Element found
35
Unit 2: ARRAYS
if (mat[i,j_mid] == x)
{
Console.WriteLine( "Found at (" + i + ", " + j_mid +")");
return;
}
else if (mat[i,j_mid] > x)
j_high = j_mid - 1;
else
j_low = j_mid + 1;
}
// element not found
Console.WriteLine ( "Element not found");
}
// element found
if (mat[i_mid,j_mid] == x)
{
Console.WriteLine ( "Found at (" + i_mid +", " + j_mid +")");
return;
}
else if (mat[i_mid][j_mid] > x)
36
Unit 2: ARRAYS
i_high = i_mid;
else
i_low = i_mid;
}
// If element is present on
// the mid of the two rows
if (mat[i_low,j_mid] == x)
Console.WriteLine ( "Found at (" + i_low + "," + j_mid +")");
else if (mat[i_low + 1,j_mid] == x)
Console.WriteLine ( "Found at (" + (i_low + 1) + ", " + j_mid
+")");
sortedMatrixSearch(mat, n, m, x);
}
}
Output:
Found at (0,2)
37
Unit 2: ARRAYS
Search in a row wise and column wise sorted matrix
Given an n x n matrix and a number x, find the position of x in the matrix if it is
present in it. Otherwise, print “Not Found”. In the given matrix, every row and
column is sorted in increasing order. The designed algorithm should have
linear time complexity.
Example:
Input: mat[4,4] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 29
Output: Found at (2, 1)
Explanation: Element at (2,1) is 29
Simple Solution
Approach: The simple idea is to traverse the array and to search element one
by one.
Algorithm:
Run a nested loop, outer loop for row and inner loop for the column.
Check every element with x and if the element is found then print “element
found”. If the element is not found, then print “element not found”.
Efficient Solution
Approach: The simple idea is to remove a row or column in each comparison
until an element is found. Start searching from the top-right corner of the
matrix. There are three possible cases:
1. The given number is greater than the current number: This will ensure,
that all the elements in the current row are smaller than the given
number as the pointer is already at the right-most element and the row
is sorted. Thus, the entire row gets eliminated and continue the search
38
Unit 2: ARRAYS
on the next row. Here elimination means that row needs not to be
searched.
2. The given number is smaller than the current number: This will ensure,
that all the elements in the current column are greater than the given
number. Thus, the entire column gets eliminated and continue the
search on the previous column i.e. the column at the immediate left.
3. The given number is equal to the current number: This will end the
search.
The search can also be started from the bottom left corner of the matrix.
Algorithm:
• Let the given element be x, create two variable i = 0, j = n-1 as index of row
and column
• Run a loop until i = 0
• Check if the current element is greater than x then decrease the count of j.
Exclude the current column.
• Check if the current element is less than x then increase the count of i.
Exclude the current row.
• If the element is equal, then print the position and end.
Implementation:
// C# Code for Search in a row wise and column wise sorted matrix
class SearchRowWiseColWise {
39
Unit 2: ARRAYS
}
Console.Write ("n Element not found");
return; // if ( i==n || j== -1 )
}
public static void main(String[] args)
{
int[,] mat = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 } };
search(mat, 4, 29);
}
}
Reflection
Now that we have finished about arrays, why do you think arrays are useful in
programming?
40
Unit 2: ARRAYS
✓ An array index can be any expression that evaluates to a nonnegative
integer. The value of the index must always be less than the size of the
array.
✓ In C#, an array index starts with 0.
✓ In C#, [] is an operator, called the array subscripting operator. When an
array object is instantiated, its elements are initialized to their default
values.
✓ Arrays that are created, that is, instantiated, during program execution
are called dynamic arrays.
✓ Arrays can be initialized when they are created.
✓ A public (final) instance variable length is associated with each array
that has been instantiated (that is, for which memory has been
allocated to
✓ A two-dimensional array is an array in which the elements are arranged
in a table form.
✓ To access an element of a two-dimensional array, you need a pair of
indices: one for the row position and one for the column position. store
the data). The variable length contains the size of the array.
✓ In row processing, a two-dimensional array is processed one row at a
time.
✓ In column processing, a two-dimensional array is processed one column
at a time.
✓ C# stores two-dimensional arrays in a row order form in computer
memory.
References