0% found this document useful (0 votes)
5 views41 pages

Module 2 Arrays

Unit 2 focuses on arrays in C#, covering their definition, types, and operations. It includes learning outcomes for one-dimensional arrays, such as declaring, initializing, accessing, and manipulating array elements. The document also discusses algorithms for searching and sorting arrays, including linear search and bubble sort.
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)
5 views41 pages

Module 2 Arrays

Unit 2 focuses on arrays in C#, covering their definition, types, and operations. It includes learning outcomes for one-dimensional arrays, such as declaring, initializing, accessing, and manipulating array elements. The document also discusses algorithms for searching and sorting arrays, including linear search and bubble sort.
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/ 41

Unit 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.

In your previous programing subjects, you learned how to read numbers,


print them, and find their sum. What’s different here is that we want to print the
numbers in reverse order. We cannot print the first four numbers until we have
printed the fifth, and so on. This means that we need to store all the numbers
before we can print them in reverse order.

Unit Learning Outcomes


At the end of the unit, you will be able to:

a. differentiate and understand the values of the different types of arrays


b. discover how to manipulate data in a one-multi-dimensional and two-
dimensional array
c. learn how to search and sort an array

Topic 1: One Dimensional Array


Time Allotment: 4 hours

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

Activating Prior Knowledge


What comes to your mind when you hear the word ARRAY? Write your answer
on the empty boxes provided below.

Presentation of Contents

An array is a collection (sequence) of a fixed number of variables


called elements or components, wherein all the elements are of the same
data type. There are 3 types of an array namely one-dimensional array, two-
dimensional array and multi-dimensional array.

One-Dimensional Array
A one-dimensional array is an array in which the elements are
arranged in a list form.

Declaring a One-Dimensional Array


The general form to declare a one-dimensional array is:

dataType[] arrayName; //Line 1

where dataType is the element type.

Because an array is an object, arrayName is a reference variable.


Therefore, the preceding statement only declares a reference variable.
Before we can store the data, we must instantiate the array object.

2
Unit 2: ARRAYS
The general syntax to instantiate an array object is:

arrayName = new dataType[intExp]; //Line 2

where intExp is any expression that evaluates to a positive integer. Also,


the value of intExp specifies the number of elements in the array.
When an array is instantiated, C# automatically initializes its elements
to their default values. For example, the elements of numeric arrays are
initialized to 0, the elements of char arrays are initialized to the null character,
which is '\u0000', the elements of boolean arrays are initialized to false.

You can combine the statements in Lines 1 and 2 into one statement
as follows:

dataType[] arrayName = new dataType[intExp]; //Line 3

The statement:

int[] num = new int[5];

declares and creates the array num consisting of 5 elements. Each


element is of type int. The elements are accessed as num[0], num[1], num[2],
num[3], and num[4]. Below
illustrates the array num.
0
0
0
0

Accessing Array Elements

The general form (syntax) used to access an array element is:

arrayName[indexExp]

where indexExp, called the index, is an expression whose value is a


nonnegative integer less than the size of the array. The index value specifies
the position of the element in the array. In C#, the array index starts at 0. In
C#, [] is an operator called the array subscripting operator.

3
Unit 2: ARRAYS
Consider the following statement:

int[] list = new int[10];

This statement declares an array list of 10 elements. The elements are


list[0], list[1], . . ., list[9]. In other words, we have declared 10 variables of type
int as shown below.

The assignment statement:

list[5] = 34;

stores 34 into list[5], which is the sixth element of the array list as shown
below.

Suppose i is an int variable. Then, the assignment statement:

list[3] = 63;
is equivalent to the assignment statements:

i = 3;
list[i] = 63;

If i is 4, then the assignment statement:

list[2 * i - 3] = 58;

stores 58 into list[5], because 2 * i - 3 evaluates to 5. The index


expression is
evaluated first, giving the position of the element in the array.

Next, consider the following statements:


list[3] = 10;
list[6] = 35;
list[5] = list[3] + list[6];

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].

Specifying Array Size during Program Execution


When you include a statement in a program to instantiate an array
object, it is not necessary to know the size of the array at compile time.
During program execution, you can first prompt the user to specify the size of
the array and then instantiate the object.

The following statements illustrate this concept:

int arraySize; //Line 1

Console.Write("Enter the size of the array: "); //Line 2


arraySize = Convert.ToInt32(Console.ReadLine()); //Line 3
Console.WriteLine(); //Line 4

int[] list = new int[arraySize]; //Line 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.

Array Initialization during Declaration


Like any other primitive data type variable, an array can also be
initialized with specific values when it is declared. For example, the following
C# statement declares an array, sales, of five elements and initializes those
elements to specific values:

double[] sales = {12.25, 32.50, 16.90, 23, 45.68};

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.

Note the following about declaring and initializing arrays:


• When declaring and initializing arrays, the size of the array is
determined by the number of initial values in the initializer list within the
braces.

5
Unit 2: ARRAYS
• If an array is declared and initialized simultaneously, we do not use the
operator new to instantiate the array object.

Arrays and the Instance Variable length


Recall that an array is an object; therefore, to store data, the array
object must be instantiated. Associated with each array that has been
instantiated (that is, for which memory has been allocated to store data),
there is a public (final) instance variable length. The variable length contains
the size of the array. Because length is a public member, it can be directly
accessed in a program using the array name and the dot operator.

Consider the following declaration:


int[] list = {10, 20, 30, 40, 50, 60};

This statement creates the array list of six elements and initializes the
elements using the values given. Here, list.Length is 6.

Consider the following statement:

int[] numList = new int[10];

This statement creates the array numList of 10 elements and initializes


each element to 0. Because the number of elements of numList is 10, the
value of numList.Length is 10.

Now consider the following statements:


numList[0] = 5;
numList[1] = 10;
numList[2] = 15;
numList[3] = 20;

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.

Note: Once an array is instantiated, its size remains fixed. In other


words, if you have instantiated an array of 5 elements, the number of
elements of the array remains 5. If you need to increase the size of the array,
then you must instantiate another array of the desired size and copy the data
stored in the first array into the new array.

6
Unit 2: ARRAYS
Processing One-Dimensional Arrays

Some basic operations performed on a one-dimensional array are


initializing the array, reading data into the array, storing output data in the
array, and finding the largest and/ or smallest element in the array. If the
data type of an array element is numeric, some common operations are to
find the sum and average of the elements of the array. Each of these
operations requires the ability to step through the elements of the array,
which is easily accomplished by using a loop. Suppose that we have the
following statements:

int[] list = new int[100]; //list is an array of size 100

The following for loop steps through each element of the array list,
starting at the first
element of list:

for (int i = 0; i < list.Length; i++) //Line 1


//process list[i], the (i + 1)th element of list //Line 2

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:

for (int i = 0; i < list.Length; i++) //Line 1


list[i] = Convert.ToInt32(Console.ReadLine()); //Line 2

Similarly, if processing list requires outputting data, then the statement


in Line 2 takes the form of an output statement. The following for loop outputs
the elements of list:

for (int i = 0; i < list.Length; i++) //Line 1


Console.Write(list[i] + " "); //Line 2

The following example shows how loops are used to process arrays. The
following declaration is used throughout this example:

double[] sales = new double[10];


double sum, average;

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:

1. Initializing an array to a specific value: Suppose that you want to


initialize every element of the array sales to 10.00. You can use the
following loop:

for (int index = 0; index < sales.Length; index++)


sales[index] = 10.00;

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.

for (int index = 0; index < sales.Length; index++)


sales[index] = double.Parse(Console.ReadLine());

3. Printing an array: The following loop outputs the elements of array sales.
For simplicity, we assume that the output goes to the screen.

for (int index = 0; index < sales.Length; index++)


Console.Write(sales[index] + " ");

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[])
{

int[ ] a={10,20,30,40,50};//declaration and initialization


Console.WriteLine("One dimensional array elements are :\n");
for(int i=0;i<a.Length;i++)

{
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.

3. Binary Search Algorithm


- A binary search algorithm is an algorithm for locating the position of an
element in a sorted list. It inspects the middle element of the sorted list: if
equal to the sought value, then the position has been found; otherwise, the
upper half or lower half is chosen for further searching based on whether the
sought value is greater than or less than the middle element. The method
reduces the number of elements needed to be checked by a factor of two
each time, and finds the sought value if it exists in the list.
- The binary search uses the “divide and conquer” strategy. It repeatedly
divides the array into two pieces and then searches the piece that could
contain the target value.

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:

o Step 1: Traverse the array


o Step 2: Match the key element with array element
o Step 3: If key element is found, return the index position of the array element
o Step 4: If key element is not found, return -1

Let's see an example of linear search in C# where we are going to search an


element sequentially from an array.

public class LinearSearchExample{


public static int linearSearch(int[] arr, int key){
for(int i=0;i<arr.Length;i++){
if(arr[i] == key){
return i;
}
}
return -1;
}
public static void main(String a[]){
int[] a1= {10,20,30,50,70,90};
int key = 50;
Console.WriteLine(key+" is found at index: "+linearSearch(a1, key));
}
}
Output:
50 is found at index: 3

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;

Console.WriteLine("Enter number of elements");


n = int.Parse(Console.ReadLine());
array = new int[n];

Console.WriteLine("Enter those " + n + " elements");

for (c = 0; c < n; c++)


array[c] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter value to find");


search = int.Parse(Console.ReadLine());

for (c = 0; c < n; c++)


{
if (array[c] == search) /* Searching element is present */
{
Console.WriteLine(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
Console.WriteLine(search + " isn't present in 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

Program to sort an array in ascending order in C#


public class ExArraySort
{
public static void main(String args[])
{
// initialize the objects.
int n, i, j, temp;
int[ ] arr = new int[50];

// enter number of elements to enter.


Console.WriteLine("Enter number for the array elements : ");
n = int.Parse(Console.ReadLine());

// enter elements.
Console.WriteLine("Enter " +n+ " Numbers : ");
for(i=0; i<n; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}

// sorting array elements.


Console.WriteLine("Sorting array : \n");
for(i=0; i<(n-1); i++)
{
for(j=0; j<(n-i-1); j++)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
Console.WriteLine("Array Sorted Successfully..!!\n");

14
Unit 2: ARRAYS

// array in ascending order.


Console.WriteLine("Sorted List in Ascending Order : \n");
for(i=0; i<n; i++)
{
Console.WriteLine(arr[i]+ " ");
}
}
}

Output

Enter number for the array elements : 10


Enter 10 Numbers :
25
54
36
12
48
88
78
95
54
55
Sorting array :
Array Sorted Successfully..!!
Sorted List in Ascending Order :
12 25 36 48 54 54 55 78 88 95

C# Program to Sort the Array in Descending Order


This is a C# Program to Sort the Array in Descending Order.
Enter size of array and then enter all the elements of that array. Now with the help of
for loop and temp variable we sort the array in descending order.
Here is the source code of the C# Program to Sort the Array in Descending Order. The
C# program is successfully compiled and run on a Windows system. The program
output is also shown below.

public class Descending_Order


{
public static void main(String[] args)
{
int n, temp;
Console.WriteLine("Enter no. of elements you want in array:");
n = int.Parse(Console.ReadLine());
int[ ] a = new int[n];
Console.WriteLine("Enter all the elements:");

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 Algorithm

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

Case 1: if target = A[mid], we return mid.


Case 2: if target < A[mid], we discard all elements in the right search space
including the mid element i.e. A[mid….high]. now our
new high would be mid-1.
Case 3: if target > A[mid], we discard all elements in the left search space including t
he mid element i.e. A[low…mid]. Now our new low would
be mid+1.
We repeat the process until target is found or our search space is exhausted.
Let’s understand this by taking an example.
Let arr = {2, 3, ,5 ,7 ,8, 10, 12, 15, 18, 20}
target = 7

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

Binary Search Algorithm


public class BinarySearch
{
// find out if a key x exists in the sorted array A
// or not using binary search algorithm
public static int binarySearch(int[] A, int x)
{
// search space is A[left..right]
int left = 0, right = A.Length - 1;

// till search space consists of at-least one element


while (left <= right)
{
// we find the mid value in the search space and
// compares it with key value

18
Unit 2: ARRAYS
int mid = (left + right) / 2;

// key value is found


if (x == A[mid]) {
return mid;
}

// discard all elements in the right search space


// including the mid element
else if (x < A[mid]) {
right = mid - 1;
}

// discard all elements in the left search space


// including the mid element
else {
left = mid + 1;
}
}

// x doesn't exist in the array


return -1;
}

public static void main(String[] args)


{
int[] A = { 2, 5, 6, 8, 9, 10 };
int key = 5;

int index = binarySearch(A, key);

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

At the end of the session, you will be able to:


a. declare and create two- and multi-dimensional arrays
b. initialize and access multi-dimensional array values
c. sort multi-dimensional array elements in ascending and descending
order
d. search for specific element in a multi-dimensional array

Activating Prior Knowledge


What comes to your mind when you hear the word ARRAY? Write your
answer on the empty boxes provided below.

20
Unit 2: ARRAYS

Presentation of Contents

Multidimensional Arrays can be defined in simple words as array of arrays.


Data in multidimensional arrays are stored in tabular form (in row major
order).
Syntax:
data_type[1st dimension,2nd dimension, ..Nth
dimension] array_name = new data_type[size1, size2,…., sizeN];
where:
• data_type: Type of data to be stored in the array. For example: int, char,
etc.
• dimension: The dimension of the array created.
For example: 1D, 2D, etc.
• array_name: Name of the array
• size1, size2, …, sizeN: Sizes of the dimensions respectively.

Examples:

Two dimensional array:


int[,] twoD_arr = new int[10,20];

Three dimensional array:


int[ , , ] threeD_arr = new int[10,20,30];

Size of multidimensional arrays: The total number of elements that can be


stored in a multidimensional array can be calculated by multiplying the size
of all the dimensions.
For example:
The array int[ , ] x = new int[10,20] can store a total of (10*20) = 200 elements.
Similarly, array int[ , , ] x = new int[5,10,20] can store a total of (5*10*20) = 1000
elements.

Two – dimensional Array (2D-Array)


Two – dimensional array is the simplest form of a multidimensional array. A
two – dimensional array can be seen as an array of one – dimensional array
for easier understanding.
Indirect Method of Declaration:
Declaration – Syntax:
data_type[ , ] array_name = new data_type[x,y];
For example: int[ , ] arr = new int[10,20];
Initialization – Syntax:
array_name[row_index,column_index] = value;
For example: arr[0,0] = 1;

21
Unit 2: ARRAYS
Example:

class TwoDim {
public static void main(String[] args)
{

int[ , ] arr = new int[10,20];


arr[0,0] = 1;

Console.WriteLine("arr[0,0] = " + arr[0,0]);


}
}

Output:
arr[0,0] = 1

Direct Method of Declaration:

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 } };

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


for (int j = 0; j < 2; j++)
ConsoleWriteLIne("arr[" + i + "][" + j + "] = "
+ arr[i,j]);
}
}

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 } };

Console.WriteLine("arr[0, 0] = " + arr[0, 0]);


}
}

Output:
arr[0, 0] = 1

Representation of 2D array in Tabular Format: A two – dimensional array can


be seen as a table 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 two –
dimensional array ‘x’ with 3 rows and 3 columns is shown below:

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 } };

for (int i = 0; i < 2; i++) {


for (int j = 0; j < 2; j++) {
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
}

Output:
12
34

Three – dimensional Array (3D-Array)


Three – dimensional array is a complex form of a multidimensional array. A
three – dimensional array can be seen as an array of two – dimensional array
for easier understanding.

Indirect Method of Declaration:


Declaration – Syntax:
data_type[ , , ] array_name = new data_type[x,y,z];
For example: int[ , , ] arr = new int[10, 20, 30];

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;

Console.WriteLine("arr[0, 0, 0] = " + arr[0, 0, 0]);

24
Unit 2: ARRAYS
}
}

Output:
arr[0, 0, 0] = 1

Direct Method of Declaration:


Syntax:
data_type[ , , ] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};

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 } } };

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


for (int j = 0; j < 2; j++)
for (int z = 0; z < 2; z++)
Console.WriteLine("arr[" + i + "][" + j + "][" + z + "] = "
+ arr[i, j, z]);
}
}

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 } } };

Console.WriteLine("arr[0][0][0] = " + arr[0, 0, 0]);


}
}

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:

Print 3D array in tabular format:


To output all the elements of a Three-Dimensional array, use nested for loops.
For this three for loops are required, One to traverse the arrays, second to
traverse the rows and another to traverse columns.
Example:
class ThreeDim {
public static void main(String[] args)
{
int[ , , ] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

Console.Write(arr[i, j, k] + " ");


}

27
Unit 2: ARRAYS

Console.WriteLine();
}
Console.WriteLine ();
}
}
}

Output:
12
34

56
78

Sort the two-dimensional (2D) array – In-place

Problem: Given a two-dimensional array where each individual row is sorted


in ascending order. Your task is to sort the entire 2d array in ascending order.
Write an algorithm for the sorting.

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 {

public static void main(String args[])


{
Console.Write("Enter the no. of rows: ");
int m = int.Parse(Console.ReadLine());
Console.Write ("Enter the no. of columns: ");
int n = int.Parse(Console.ReadLine());
int[ , ] A = new int[m,n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
Console.Write ("Enter the elements: ");
A[i,j] = int.Parse(Console.ReadLine());
}
}

Console.WriteLine ("The original matrix:");


for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
Console.Write(A[i,j]+"\t");
}
Console.WriteLine();
}

/* Sorting the 2D Array */


int t=0;
for(int x=0;x<m;x++)
{
for(int y=0;y<n;y++)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(A[i,j]>A[x,y])
{
t = A[x,y];
A[x,y] = A[i,j];
A[i,j] = t;
}
}
}

31
Unit 2: ARRAYS
}
}

Console.WriteLine("The Sorted Array:");


for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
Console.Write(A[i,j]+"\t");
}
Console.WriteLine();
}

}
}

Output:

Enter the no. of rows: 2


Enter the no. of columns: 3
Enter the elements: 5
Enter the elements: 12
Enter the elements: 17
Enter the elements: 1
Enter the elements: 2
Enter the elements: 4
The original matrix:
5 12 17
1 2 4
The Sorted Array:
1 2 4
5 12 17

GetLength(Int32) Method is used to find the total number of elements present


in the specified dimension of the Array.
Syntax: public int GetLength (int dimension);
Here, dimension is a zero-based dimension of the Array whose length needs
to be determined.

The .GetLength(0) method returns the number of elements in the first


dimension of the Array.

The .GetLength(1) method returns number of elements in the column


direction in a multidimensional array.

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

Search element in a sorted matrix


Given a sorted matrix mat[n,m] and an element ‘x’. Find position of x in the
matrix if it is present, else print -1. Matrix is sorted in a way such that all
elements in a row are sorted in increasing order and for row ‘i’, where 1 <= i
<= n-1, first element of row 'i' is greater than or equal to the last element of
row 'i-1'.

Examples:

Input : mat[,] = { {1, 5, 9},


{14, 20, 21},
{30, 34, 43} };
x = 14
Output : Found at (1, 0)

Input : mat[,] = { {1, 5, 9, 11},


{14, 20, 21, 26},
{30, 34, 43, 50} };
x = 42
Output : -1

A Simple Solution is to one-by-one compare x with every element of matrix. If


it matches, then return position. If we reach end, return -1.
An efficient solution is to typecast (convert) given 2D array to 1D array, then
apply binary search on the typecasted array.

Another efficient approach that doesn’t require typecasting is explained


below.

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)

Now, only two rows are left


| 1 2 3 4|
x = 3, mat = | 5 6 7 8| Check whether element is present on the middle
elements of these rows = {2, 6} x != 2 or 6

If not, consider the four sub-parts


1st half of 1st row = {1}, 2nd half of 1st row = {3, 4}
1st half of 2nd row = {5}, 2nd half of 2nd row = {7, 8}

According to the value of 'x' it will be searched in the


2nd half of 1st row = {3, 4} and found at (0, 2)

// 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");
}

// Function to perform binary search on the mid


// values of row to get the desired pair of rows
// where the element can be found

static void sortedMatrixSearch(int[,] mat, int n, int m, int x)


{
// Single row matrix
if (n == 1)
{
binarySearch(mat, 0, 0, m - 1, x);
return;
}
// Do binary search in middle column.
// Condition to terminate the loop when the
// 2 desired rows are found
int i_low = 0;
int i_high = n - 1;
int j_mid = m / 2;
while ((i_low + 1) < i_high)
{
int i_mid = (i_low + i_high) / 2;

// 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
+")");

// Search element on 1st half of 1st row


else if (x <= mat[i_low,j_mid - 1])
binarySearch(mat, i_low, 0, j_mid - 1, x);

// Search element on 2nd half of 1st row


else if (x >= mat[i_low,j_mid + 1] && x <= mat[i_low,m - 1])
binarySearch(mat, i_low, j_mid + 1, m - 1, x);

// Search element on 1st half of 2nd row


else if (x <= mat[i_low + 1,j_mid - 1])
binarySearch(mat, i_low + 1, 0, j_mid - 1, x);

// search element on 2nd half of 2nd row


else
binarySearch(mat, i_low + 1, j_mid + 1, m - 1, x);
}

public static void main (String[] args)


{
int n = 4, m = 5, x = 8;
int[,] mat = {{0, 6, 8, 9, 11},
{20, 22, 28, 29, 31},
{36, 38, 50, 61, 63},
{64, 66, 100, 122, 128}};

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

Input : mat[4,4] = { {10, 20, 30, 40},


{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}};
x = 100
Output : Element not found
Explanation: Element 100 is not found

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”.

A better solution is to use Divide and Conquer to find the element

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 {

/* Searches the element x in mat[,]. If the element is found, then prints


its position and returns true, otherwise prints "not found" and returns false */

private static void search(int[,] mat, int n, int x)


{
int i = 0, j = n - 1;
// set indexes for top right element

while (i < n && j >= 0) {


if (mat[i,j] == x) {
Console.Write("n Found at " + i + " " + j);
return;
}
if (mat[i,j] > x)
j--;
else
i++;

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?

Summary of the Unit


✓ An array is a structured data type with a fixed number of elements. Every
element is of the same type, and the elements are accessed using their
relative positions in the array.
✓ Elements of a one-dimensional array are arranged in the form of a list.

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

Data Structures and Algorithms in C# Michael T. Goodrich Department of


Computer Science University of California, Irvine 1 Roberto Tamassia
Department of Computer Science Brown University 0-471-73884-0 Fourth
Edition
C# Programming From Program Analysis to Program Design, D. S. Malik,
Fourth Edition

Retrieved from https://www.geeksforgeeks.org/multidimensional-arrays-in-


C#/

Retrieved from https://algorithms.tutorialhorizon.com/sort-the-two-


dimensional-2d-array-in-place/
Retrieved from https://www.geeksforgeeks.org/search-element-sorted-
matrix/
Retrieved from https://www.geeksforgeeks.org/search-in-row-wise-and-
column-wise-sorted-matrix/
41

You might also like