CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays Prof. Amr Goneid, AUC 1
Arrays Prof. Amr Goneid, AUC 2
1-D Arrays Data Structures The Array Data Type How to Declare an Array Operations on Arrays Passing to and from Functions Examples Example Functions Prof. Amr Goneid, AUC 3
1. Data Structures Data Set Linear Tree Graph Prof. Amr Goneid, AUC 4
Data Structures Sets: No structure, just membership. Linear: Sequential, one-to-one. e.g Arrays, Strings and Streams Tree: Non-Linear, one-to-many. Graph: Non-Linear, many-to-many. Arrays, Structures and Classes are used to model different data structures. Prof. Amr Goneid, AUC 5
2. The Array Data Type Array elements have a common name The array as a whole is referenced through the common name Array elements are of the same type the base type Individual elements of the array are referenced by sub_scripting the group name by an index Prof. Amr Goneid, AUC 6
1-D Arrays Prof. Amr Goneid, AUC 7
1-D Arrays Linear Data Structure (One-To-One) Fixed Size n (Static) All elements are of the same type An element is accessed by an ordinal index with values between a lower bound (0) and an upper bound (n-1) 0 index n -1 Prof. Amr Goneid, AUC 8
Array Size Size = No. of Elements = n UB = n - 1 Number of Bytes = size * Element size. All elements are of the same size. Maximum size of 64 Kbytes. 0 250 elements = 500 bytes 249 int 0 26 elements = 104 bytes 25 float Prof. Amr Goneid, AUC 9
3. How to Declare an Array Syntax: <basetype> <name> [size] ; e.g. int a [20] ; float x [101] ; const Maxelem = 200; typedef int itemtype; itemtype y [Maxelem+1]; string name [51]; enum color {red, green, blue}; color pixel [201]; int npixels[3]; Prof. Amr Goneid, AUC 10
Sample Declarations Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000; Prof. Amr Goneid, AUC 11
Sample Declarations Then the following are all correct array declarations. int A[10]; char B[MaxStringSize]; float C[M*N]; int Values[MaxListSize]; Rational D[N-15]; Prof. Amr Goneid, AUC 12
4. Operations on Arrays Declaration with Initialization: e.g. int x [6] = {12, 23, 56, 34, 18, 20}; char g[ ] = { A, B, C, D, F }; //This sets the size of the array g to 5 elements Prof. Amr Goneid, AUC 13
Operations on Arrays Accessing an Element: <array name>[index] 0 =< index =< UB index (location of element in the array) can be a const, variable or any integral / ordinal expression. e.g. x[2] or y[i] or x[2*n+1] Prof. Amr Goneid, AUC 14
Operations on Arrays Index manipulation: int i = 7, j = 2, k = 4; A[0] = 1; A[i] = 5; A[j] = A[i] + 3; A[j+1] = A[i] + A[0]; A[A[j]] = 12; Prof. Amr Goneid, AUC 12 15
Operations on Arrays Warning C++ will not flag an error if the array subscript goes out of bounds Ex: int B[10]; // declare B with 10 elements B[20] = 2; // subscript out of range This is allowed by the compiler, but will lead to unpredictable behavior Beware! Prof. Amr Goneid, AUC 12 16
Operations on Arrays Retrieve an element: e.g. z = x[ i ] ; Update an element: e.g. name[ i ] = Ann ; pixel[100] = red; npixels[green] ++ ; Input an element of an array: cin >> x[i]; Output an element of an array: cout << x[i]; Prof. Amr Goneid, AUC 17
5. Passing to and from Functions Passing an array element as a parameter: e.g. void swap ( int &a, int &b); invoke as swap ( x[i], x[j] ) ; Passing an entire array by reference: e.g. int findmax ( int x [ ], int size ); invoke as m = findmax ( x, n); Prof. Amr Goneid, AUC 18
Remember Arrays are always passed by reference Can use const if array elements are not to be modified, e.g. int findmax ( const int x [ ], int size ); You do not need to include the array size within the brackets when defining an array parameter. This is because the array name is the base address of the array, and the size is already known. Prof. Amr Goneid, AUC 19
6. Examples A function to input n elements of an integer array and return the array and n as parameters: const MAX_SIZE = 200; int a [MAX_SIZE]; void input_array ( int a[ ], int &n ) { int n = 0; int v; while((n < MAX_SIZE) && (cin >> v)) { a[n] = v; n++; } } Prof. Amr Goneid, AUC 20
Examples A function that receives an integer array and lists the first n elements of the array : void output_array ( const int a[ ], int n ) { for (int i = 0 ; i < n ; i++) cout << a[i] << ; cout << endl; } Prof. Amr Goneid, AUC 21
Examples A function to receive an integer array and return the index of the minimum element in the sub-array starting at index (s) and ending at index (e): int index_of_min ( int a[ ], int s, int e ) { int imin = s; for (int i = s+1; i <= e ; i++) if (a[i] < a[imin]) imin = i ; return imin ; } Prof. Amr Goneid, AUC 22
Examples A function to receive a real array and return the average value of the elements. float average( float x[ ], int n ) { float sum = 0; for (int i = 0; i < n ; i++) sum += x[i]; return (sum / float (n)) ; } Prof. Amr Goneid, AUC 23
7. Example Functions Function1: Computing the Average and Standard Deviation of a list of numbers. Function2: Linear (Sequential) Search in an array. Function3: Sorting an array using Selection Sort. Function4: Sorting an array using Bubble Sort Function5: Searching an array using Binary Search Prof. Amr Goneid, AUC 24
Function 1: Average & Standard Deviation The average (av) of array x[0..n-1] is computed as the sum of all elements divided by n. The variance is defined as the average of the squared deviations from the average value. The Standard Deviation is the square root of the variance. n 1 n 1 1 1 x = xi, v = i = n n i= 0 i= 0 2 ( x x ), σ v Prof. Amr Goneid, AUC 25
Function stat void stat ( const float x[ ], int n, float &av, float &sd) { float d; float var = 0; av = average(x,n); for (int i = 0; i < n ; i++) { d = x[i] av ; var += d*d; } sd = sqrt(var / float(n)); } Prof. Amr Goneid, AUC 26
Function 2: Linear Search The idea of a linear search is to walk through the entire array until a target value is located. If found, its location is returned. If the target is not located some type of indicator needs to be returned Prof. Amr Goneid, AUC 27
Linear Search Function // Searches an integer array of size (n) // for a given element (the target) // Array elements ranging from 0 to // n - 1 are searched for an element // equal to target. // Returns the subscript of target if // found; otherwise, returns -1. Prof. Amr Goneid, AUC 28
linsearch Function (Cont.) int linsearch (const int a[ ], int target, int n) { for (int i = 0; i < n; i++) if (a[i] == target) return i; // All elements were tested without success. return -1; } // end linsearch Prof. Amr Goneid, AUC 29
Function 3: Selection Sort Assume elements to be in locations 0..n-1 Let (i) be the start of a sub-array of at least 2 elements, i.e. i = 0.. n-2 for each i = 0.. n-2 find smallest element in sub-array a[i] to a[n-1]. swap that element with that at the start of the sub-array. Prof. Amr Goneid, AUC 30
How it works 4 3 1 6 2 5 1 3 4 6 2 5 1 2 4 6 3 5 1 2 3 6 4 5 1 2 3 4 6 5 1 2 3 4 5 6 Prof. Amr Goneid, AUC 31
Selection Sort Algorithm void selectsort (itemtype a[ ], int n) { int i, j, m; for (i = 0; i < n-1; i++) { m = i ; for ( j = i+1; j < n; j++) if (a[j] < a[m]) m = j ; swap (a[i], a[m]); } } Prof. Amr Goneid, AUC 32
Function 4: Bubble Sort The general idea is to compare adjacent elements and swap if necessary Assume elements to be in locations 0..n-1 Let (i) be the index of the last element in a subarray of at least 2 elements, i.e. i = n-1.. 1 Prof. Amr Goneid, AUC 33
Bubble Sort Algorithm for each i = n-1 1 Compare adjacent elements a j and a j+1, j = 0..i-1 and swap them if a j > a j+1 This will bubble the largest element in the sub-array a[0..i] to location (i). Prof. Amr Goneid, AUC 34
How it works 4 3 1 2 3 4 1 2 3 1 4 2 3 1 2 4 1 3 2 4 1 2 3 4 Prof. Amr Goneid, AUC 35
Bubble Sort Algorithm void bubblesort (itemtype a[ ], int n) { int i, j; bool swapped; for (i = n; --i >= 0; ) { swapped = false; for (j = 0; j < i; j++) { if (a[j] > a[j+1] ) { swap(a[j], a[j+1]); swapped = true; } } if (!swapped) return; } } Prof. Amr Goneid, AUC 36
Function 5: Binary Search Prof. Amr Goneid, AUC 37
Binary Search: How it works Assume elements in locations a[1]..a[n] to be already sorted in ascending order put the key (x) we are searching for in location a[0]. Set Low index L=1 and High index H=n Let (m) be the index of the approximate middle between L and H do compute middle location (m) if (L > H) there is no hope to find (x) in the array, so set m = 0 else if x < a[m] discard a[m]..a[h] by setting H = m-1, else if x > a[m] discard a[1]..a[m] by setting L = m+1, else, x is found at a[m] while x is not yet found at a[m] return the location (m), if zero it is not found Prof. Amr Goneid, AUC 38
Binary Search Algorithm int binsearch (itemtype a[ ], int n, itemtype x) { int L, m, H; a[0] = x; L = 1; H = n; do { m = (L + H)/2; if (L > H) m = 0; else if (x < a[m]) H = m-1; else L = m+1; } while (a[m]!= x); return m; } Prof. Amr Goneid, AUC 39
2-D Arrays Prof. Amr Goneid, AUC 40
2-D Arrays Declaration & Indexing 2-D Arrays as Parameters Simple Matrix Operations Other Applications Prof. Amr Goneid, AUC 41
2-D Arrays Useful in representing a variety of data, e.g. Tables, Matrices, Graphs and Images Day Fri Sat Sun j City Cairo 35 32 33 i 5 2 3 Tanta 34 31 31 4 1 1 Alex 29 28 28 9 8 8 A Table of Temp. A Matrix of Integers Prof. Amr Goneid, AUC 42
2-D Arrays Bit Map Color Image Zoomed showing Pixels Prof. Amr Goneid, AUC 43
Declaration & Indexing Declaration: <element-type> <arrayname> [size 1][size2]; e.g. double table[nrows] [NCOLS]; Indexing: table[2] [4]; Row# 0.. NROWS Column# 0.. NCOLS Prof. Amr Goneid, AUC 44
Example const int NRows = 11; const int Seats_In_Row = 9; string seatplan [NRows][Seats_In_Row]; Prof. Amr Goneid, AUC 45
Initialization const int NRows = 2; const int NCols = 3; float matrix[nrows][ncols] ={{5.0,4.5, 3.0}, {-16.0, -5.9, 0.0}}; We use nested loops with twodimensional arrays Prof. Amr Goneid, AUC 46
2-D Arrays as Parameters In 1-D arrays, it is not necessary to specify the size: void display (int A[ ], int n); To follow the same convention with 2-D arrays: void display (int B[ ] [ ], int n, int m); This will not work, because 2-D arrays are stored as 1-D arrays of arrays (1-D arrays of rows) Hence, beside the base address (name) we must also specify the number of columns, e.g. void display (int B[ ][Ncol], int n, int m); Prof. Amr Goneid, AUC 47
SumArray.cpp // FILE: SumArray.cpp // CALCULATES THE SUM OF THE ELEMENTS IN THE // FIRST rows ROWS OF AN ARRAY OF FLOATING POINT // VALUES WITH NCOLS (A CONSTANT) COLUMNS. // Pre: The type int constant NCOLS is // defined (NCOLS > 0) and the // array element values are defined and rows > 0. // Post: sum is the sum of all array element // values. // Returns: Sum of all values stored in the // array. Prof. Amr Goneid, AUC 48
SumArray.cpp float sumarray (float a[ ][NCOLS], int rows) { float sum = 0.0; // Add each array element value to sum. for (int r = 0; r < rows; r++) for (int c = 0; c < NCOLS; c++) sum += a[r][c]; } return sum; Prof. Amr Goneid, AUC 49
Higher Dimensions const int people = 10; const int years = 5; money sales[people][years][12]; Prof. Amr Goneid, AUC 50
Simple Matrix Operations Matrix Addition Matrix Transpose Matrix Multiplication Prof. Amr Goneid, AUC 51
Matrix Addition Given two matrices of the same dimensions A nm and B nm. Their sum is a matrix of the same dimensions C nm such that C ij = A ij + B ij Prof. Amr Goneid, AUC 52
Matrix Addition // N, M are global constants void matadd (float A[ ] [M], float B[ ] [M], float C[ ] [M]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) C[i][j] = A[i][j] + B[i][j]; } Prof. Amr Goneid, AUC 53
Matrix Transpose Given a matrix A nm, its transpose is A T = B mn with elements B ji = A ij // N, M are global constants void mattranspose (float A[ ] [M], float B[ ] [N]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) B[j][i] = A[i][j] ; } Prof. Amr Goneid, AUC 54
Example:Matrix Multiplication // Multiply matrix A(N rows x L columns) by matrix // B(L rows x M columns) to produce a matrix // C(N rows x M columns). // The elements of matrix C are: // C(i,j) = sum over k from 1 to L of {A(i,k) * B(k,j)} // with i = 1 to N, j = 1 to M // N, M, L are global constants Prof. Amr Goneid, AUC 55
Matrix Multiplication void matmult (float A[ ] [L], float B[ ] [M], float C[ ] [M]) { for (int i = 0; i < N; i++) for (int j = 0; j < M; j++) { C[i][j] = 0; for (int k = 0; k < L; k++) C[i][j] += A[i][k] * B[k][j]; } } Prof. Amr Goneid, AUC 56
Image Application Image A has random gray levels between 0(Black) and 255(White). What is the algorithm used to convert Image A to the binary image B? Image A Image B Prof. Amr Goneid, AUC 57
Image Application Same algorithm would do this. 256 Gray Levels 2 Levels(Binary) Prof. Amr Goneid, AUC 58
Flip Left to Right Prof. Amr Goneid, AUC 59
Flip Upside Down Prof. Amr Goneid, AUC 60
Flip 90 Degrees to the Left Prof. Amr Goneid, AUC 61