0% found this document useful (0 votes)
60 views

Two Dimensional Arrays: Mirza Mohammad Lutfe Elahi

This document discusses two-dimensional arrays. It begins by outlining searching and sorting algorithms, including linear and binary search. It then explains what 2D arrays are and how they can be used to store data like student grades across multiple courses. The document demonstrates how to declare, initialize, and access elements of a 2D array using row and column indices. It also provides examples of nested loops to process 2D array elements row-wise or column-wise.
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)
60 views

Two Dimensional Arrays: Mirza Mohammad Lutfe Elahi

This document discusses two-dimensional arrays. It begins by outlining searching and sorting algorithms, including linear and binary search. It then explains what 2D arrays are and how they can be used to store data like student grades across multiple courses. The document demonstrates how to declare, initialize, and access elements of a 2D array using row and column indices. It also provides examples of nested loops to process 2D array elements row-wise or column-wise.
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/ 24

Two Dimensional Arrays

Mirza Mohammad Lutfe Elahi


CSE 115 Programming Language I ECE@NSU
2

Outline

• Searching: Linear and Binary Search

• Sorting: Selection Sort

• 2D Arrays

CSE 115 Programming Language I ECE@NSU


3

Searching
• Traversing an array to locate a particular item

• It requires the user to specify the target item

• If the target item is found, its index is returned

• If the target item is NOT found, -1 is returned

• Two searching algorithms


– Linear Search (works with any array)

– Binary Search (works if the searched array is sorted)

CSE 115 Programming Language I ECE@NSU


4

Algorithm – Linear Search


1. Initialize a flag (zero) to indicate whether target is found
2. Start at the first array element (at index 0)
3. Repeat while the target is not found and there are more array
elements
If the current element matches the target then
Set the flag to indicate that the target is found
Else, Advance to the next array element
4. If the target is found then
Return the target index as the search result
Else, Return -1 as the search result

CSE 115 Programming Language I ECE@NSU


5

Linear Search Implementatio


/* Search array a[] for target using linear search
* Returns index of target or -1 if not found */
int linear_search(const int a[], int target, int n) {
int i = 0, found = 0;

while(!found && i<n) {


if(a[i] == target) For an array of n elements,
found = 1; linear search uses an
else average of n/2
++i; comparisons to find an
} item. The worst case being
if(found) return i; n comparisons.
else return -1;
}

CSE 115 Programming Language I ECE@NSU


6

Binary Search Algorithm


• If an array is ordered, it is a waste of time to look for
an item using linear search. It would be like looking
for a word in a dictionary sequentially.
• Binary search works by comparing the target with
the item at the middle of the array:
1. If the target is the middle item, we are done.
2. If the target is less than the middle item, we search the first
half of the array.
3. If the target is bigger than the middle item, we search the
second half of the array.
• Repeat until target is found or nothing to search

CSE 115 Programming Language I ECE@NSU


7
first mid last
Binary Search 0 5 11 target = 22

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

4 7 8 10 14 21 22 36 54 71 85 92
first mid last
22>21 6 8 11

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

4 7 8 10 14 21 22 36 54 71 85 92
first mid last
6 6 7 22<54

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11]

4 7 8 10 14 21 22 36 54 71 85 92

22==22
CSE 115 Programming Language I ECE@NSU
8

Binary Search Implementation


int binary_search (int a[], int target, int n) {
int first = 0, last = n - 1, mid;

while(first <= last) { /* more to search */


mid = (first + last)/2;
if(target == a[mid])
return mid; /* target found */
else if(target < a[mid])
last = mid – 1;
else
first = mid + 1;
}
return -1; /* target not found */
}

CSE 115 Programming Language I ECE@NSU


9

Sorting
• Sorting is the ordering of a collection of data
• It is a common activity in data management
• Many programs execute faster if the data they process
are sorted before processing begins
• Other programs produce more understandable output
if the data displayed is sorted
• Many sorting algorithms have been designed
• We shall consider the Selection Sort method.

CSE 115 Programming Language I ECE@NSU


10

Algorithm - Selection Sort


• Find the index of the smallest
element in the array.
• Swap the smallest element
with the first element.
• Repeat for the 2nd, 3rd, …next
smallest element.

CSE 115 Programming Language I ECE@NSU


11

CSE 115 Programming Language I ECE@NSU


12

Smallest Element in Sub-Array


/* Find the smallest element in the sub-array list[first]
* through list[last], where first<last
* Return the index of the smallest element in sub-array
*/

int get_min_range(int list[], int first, int last) {


int i;
int index_min = first;
for(i = first + 1; i <= last; i++) {
if(list[i] < list[index_min])
index_min = i;
}
return index_min;
}
CSE 115 Programming Language I ECE@NSU
13

Two-Dimensional Arrays
• A 2D array is a contiguous collection of elements of
the same type, that may be viewed as a table
consisting of multiple rows and multiple columns.
Column
0 1 2 3
0
Row 1
2

• To store the grades of 30 students in five courses, it is


better to use a 2D array than five 1D arrays.

CSE 115 Programming Language I ECE@NSU


14

2D Array Declaration
• A 2D array is declared by specifying the type of
element, the name of the variable, followed by the
number of rows and the number of columns
• As with 1D arrays, it is a good practice to declare the
row and column sizes as named constants:
#define ROWS 3 Column
#define COLS 4 0 1 2 3
0
. . .
Row 1
int table[ROWS][COLS]; 2
Both rows and columns are indexed from zero.

CSE 115 Programming Language I ECE@NSU


15

2D Array Declaration
• A 2D array element is indexed by specifying its
row and column indices.
• The following statement stores 64 in the cell
with row index 1, and column index 3:
0 1 2 3
table[1][3] = 51; 0
1 51
• Here is another example: 2
0 1 2 3
table[2][3] = 0
table[1][3] + 6; 1 51
2 57
CSE 115 Programming Language I ECE@NSU
16

Initialization 2D Arrays
• As with 1-D arrays, you can declare and initialize a 2D array at
the same time.
• A nested list is used, where each inner list represents a row. For
example:
int table[][4] = {{1,2,2,5},{3,4,6},{5,6,7,9}};

0 1 2 3
It is ok to omit the number 0 1 2 2 5
of rows but not the 1 3 4 6 0
number of columns 2 5 6 7 9

• If you provide less values than the declared size, the remaining
cells are set to zero (NOT a good practice!)

CSE 115 Programming Language I ECE@NSU


17

Processing 2D Arrays
• To process a 2D array, we use a nested loop, and
traverse the 2D array either row-wise or column-wise
• To process the elements row-wise, we write:
for(i = 0; i < ROWS; i++)
for(j = 0; j < COLS; j++) {
/* process table[i][j] */
}
• To process the elements column-wise, we write:
for(j = 0; j < COLS; j++)
for(i = 0; i < ROWS; i++) {
/* process table[i][j] */
}
CSE 115 Programming Language I ECE@NSU
18

2D Array as a Parameter
• As with 1D arrays, it is possible to declare a function
that takes a 2D array as a parameter.
• The size of the first dimension (number of rows) need
not be specified in the 2D array parameter.
• However, the size of the second dimension (columns)
must be specified as a constant.
• One solution is to use a named constant defining the
maximum number of columns and use additional
parameters for the actual size of the 2D array:
void read_2d(double a[][COLS], int r, int c);
CSE 115 Programming Language I ECE@NSU
19

Program to Add 2D Arrays


#include <stdio.h>
#define ROWS 10 /* maximum number of rows */
#define COLS 10 /* maximum number of cols */

void read_2d(double a[][COLS], int r, int c);

void add_2d(double a[][COLS],


double b[][COLS],
double s[][COLS], int r, int c);

void print_2d(double a[][COLS], int r, int c);

CSE 115 Programming Language I ECE@NSU


20

Function to Read a 2D Array


void read_2d(double a[][COLS], int r, int c) {

int i, j;

printf("Enter a table with %d rows\n", r);


printf("Each row having %d numbers\n", c);

for(i = 0; i < r; i++)


for(j = 0; j < c; j++)
scanf("%lf", &a[i][j]);
}

CSE 115 Programming Language I ECE@NSU


21

Function to Add Two 2D Arrays


void add_2d(double a[][COLS],
double b[][COLS],
double s[][COLS], int r, int c) {

int i, j;

for(i = 0; i < r; i++)


for(j = 0; j < c; j++)
s[i][j] = a[i][j] + b[i][j];
}

CSE 115 Programming Language I ECE@NSU


22

Function to Print a 2D Array


void print_2d(double a[][COLS], int r, int c) {

int i, j;

for(i = 0; i < r; i++) {


for(j = 0; j < c; j++)
printf(" %6.1f", a[i][j]);
printf("\n");
}
}

CSE 115 Programming Language I ECE@NSU


Main Function
23
int main(void) {
double x[ROWS][COLS], y[ROWS][COLS], z[ROWS][COLS];
int rows, cols;

printf("Enter number of rows: ");


scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

read_2d(x, rows, cols); /* read matrix x */


read_2d(y, rows, cols); /* read matrix y */
add_2d(x, y, z, rows, cols); /* Add x + y */

printf("The sum of two matrices is:\n");


print_2d(z, rows, cols); /* Print matrix z */

return 0;
}
CSE 115 Programming Language I ECE@NSU
24

Sample Run

CSE 115 Programming Language I ECE@NSU

You might also like