Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays.

Similar presentations


Presentation on theme: "Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays."— Presentation transcript:

1 Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

2 Prof. Amr Goneid, AUC2 Arrays

3 3 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

4 Prof. Amr Goneid, AUC4 1. Data Structures Data SetLinearTreeGraph

5 Prof. Amr Goneid, AUC5 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.

6 Prof. Amr Goneid, AUC6 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

7 Prof. Amr Goneid, AUC7 1-D Arrays

8 Prof. Amr Goneid, AUC8 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) 0n -1 index

9 Prof. Amr Goneid, AUC9 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. int 0249 float 0 25 250 elements = 500 bytes 26 elements = 104 bytes

10 Prof. Amr Goneid, AUC10 3. How to Declare an Array Syntax: [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];

11 Prof. Amr Goneid, AUC11 Sample Declarations Suppose const int N = 20; const int M = 40; const int MaxStringSize = 80; const int MaxListSize = 1000;

12 Prof. Amr Goneid, AUC12 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];

13 Prof. Amr Goneid, AUC13 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

14 Prof. Amr Goneid, AUC14 Operations on Arrays Accessing an Element: [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]

15 Prof. Amr Goneid, AUC15 12 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;

16 Prof. Amr Goneid, AUC16 12 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!

17 Prof. Amr Goneid, AUC17 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];

18 Prof. Amr Goneid, AUC18 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);

19 Prof. Amr Goneid, AUC19 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.

20 Prof. Amr Goneid, AUC20 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 > v)) { a[n] = v;n++; } }

21 Prof. Amr Goneid, AUC21 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; }

22 Prof. Amr Goneid, AUC22 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 ; } Examples

23 Prof. Amr Goneid, AUC23 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)) ; }

24 Prof. Amr Goneid, AUC24 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

25 Prof. Amr Goneid, AUC25 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.

26 Prof. Amr Goneid, AUC26 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)); }

27 Prof. Amr Goneid, AUC27 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

28 Prof. Amr Goneid, AUC28 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.

29 Prof. Amr Goneid, AUC29 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

30 Prof. Amr Goneid, AUC30 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.

31 Prof. Amr Goneid, AUC31 How it works 431625 134625 124635 123465 123645 123456

32 Prof. Amr Goneid, AUC32 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]); }

33 Prof. Amr Goneid, AUC33 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 sub- array of at least 2 elements, i.e. i = n-1.. 1

34 Prof. Amr Goneid, AUC34 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).

35 Prof. Amr Goneid, AUC35 How it works 4312 3412 3142 1324 3124 1234

36 Prof. Amr Goneid, AUC36 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; }

37 Prof. Amr Goneid, AUC37 Function 5: Binary Search

38 Prof. Amr Goneid, AUC38 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

39 Prof. Amr Goneid, AUC39 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; }

40 Prof. Amr Goneid, AUC40 2-D Arrays

41 Prof. Amr Goneid, AUC41 2-D Arrays Declaration & Indexing 2-D Arrays as Parameters Simple Matrix Operations Other Applications

42 Prof. Amr Goneid, AUC42 2-D Arrays Useful in representing a variety of data, e.g. Tables, Matrices, Graphs and Images 353233 3431 2928 City Cairo Tanta Alex DayFriSatSun 523 411 988 i j A Table of Temp. A Matrix of Integers

43 Prof. Amr Goneid, AUC43 2-D Arrays Bit MapColor Image Zoomed showing Pixels

44 Prof. Amr Goneid, AUC44 Declaration & Indexing Declaration: [size 1][size2]; e.g. double table[NROWS] [NCOLS]; Indexing: table[2] [4]; Row# 0.. NROWS Column# 0.. NCOLS

45 Prof. Amr Goneid, AUC45 Example const int NRows = 11; const int Seats_In_Row = 9; string seatPlan [NRows][Seats_In_Row];

46 Prof. Amr Goneid, AUC46 Initialization We use nested loops with two- dimensional arrays const int NRows = 2; const int NCols = 3; float matrix[NRows][NCols] ={{5.0,4.5, 3.0}, {-16.0, -5.9, 0.0}};

47 Prof. Amr Goneid, AUC47 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);

48 Prof. Amr Goneid, AUC48 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.

49 Prof. Amr Goneid, AUC49 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; }

50 Prof. Amr Goneid, AUC50 Higher Dimensions const int people = 10; const int years = 5; money sales[people][years][12];

51 Prof. Amr Goneid, AUC51 Simple Matrix Operations Matrix Addition Matrix Transpose Matrix Multiplication

52 Prof. Amr Goneid, AUC52 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

53 Prof. Amr Goneid, AUC53 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]; }

54 Prof. Amr Goneid, AUC54 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] ; }

55 Prof. Amr Goneid, AUC55 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

56 Prof. Amr Goneid, AUC56 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]; }

57 Prof. Amr Goneid, AUC57 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 AImage B

58 Prof. Amr Goneid, AUC58 Image Application Same algorithm would do this. 256 Gray Levels2 Levels(Binary)

59 Prof. Amr Goneid, AUC59 Flip Left to Right

60 Prof. Amr Goneid, AUC60 Flip Upside Down

61 Prof. Amr Goneid, AUC61 Flip 90 Degrees to the Left


Download ppt "Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays."

Similar presentations


Ads by Google