Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 5.1 One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data.

Similar presentations


Presentation on theme: "1 5.1 One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data."— Presentation transcript:

1 1 5.1 One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data structure to represent several variables having the same data type: int y[100]; y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]

2 2 One-Dimensional Arrays (cont’d) An element of an array is accessed using the array name and an index or subscript, for example: y[5] which can be used like a variable In C, the subscripts always start with 0 and increment by 1, so y[5] is the sixth element The name of the array is the address of the first element and the subscript is the offset y[0] y[1] y[2] … y[k-1] y[k] y[k+1] … y[98] y[99]

3 3 Definition and Initialization An array is defined using a declaration statement. data_type array_name[size]; allocates memory for size elements subscript of first element is 0 subscript of last element is size-1 size must be a constant

4 4 Example int list[5]; allocates memory for 5 integer variables subscript of first element is 0 subscript of last element is 4 C does not check bounds on arrays list[6] =5; /* may give segmentation fault or overwrite other memory locations*/ list[0] list[1] list[2] list[3] list[4]

5 5 Initializing Arrays Arrays can be initialized at the time they are declared. Examples: double taxrate[3] ={0.15, 0.25, 0.3}; char list[5] = {‘h’, ’e’, ’l’, ’l’, ’o’}; double vector[100] = {0.0}; /* assigns zero to all 100 elements */ int s[] = {5,0,-5}; /*the size of s is 3*/

6 6 Assigning values to an array For loops are often used to assign values to an array Example: int list[5], i; for(i=0; i<5; i++){ list[i] = i; } list[0] list[3] list[4] list[1] list[2] 0 1 2 3 4 list[0] list[1] list[2] list[3] list[4] OR for(i=0; i<=4; i++){ list[i] = i; }

7 7 Assigning values to an array Give a for loop to assign the below values to list int list[5], i; for(i=0; i<5; i++){ list[i] = 4-i; } list[0] list[3] list[4] list[1] list[2] 4 3 2 1 0

8 Matrix math in c++ Matrix addition Matrix subtraction Matrix multiplications

9 Adding Matrix #include using namespace std; int main() { int rows_a = 3, rows_b = 3, cols_a = 3, cols_b = 3; int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }; int b[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }; int c[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // int sum = 0; //for (int k = 0; k < 3; k++) c[i][j] = a[i][j] + b[i][j]; cout << "c[ " << i << " ][ " << j << " ] = " << c[i][j] << endl; } system("pause"); }

10 Subtract matrix #include using namespace std; int main() { int rows_a = 3, rows_b = 3, cols_a = 3, cols_b = 3; int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }; int b[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }; int c[3][3]; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { // int sum = 0; //for (int k = 0; k < 3; k++) c[i][j] = a[i][j] - b[i][j]; cout << "c[ " << i << " ][ " << j << " ] = " << c[i][j] << endl; } system("pause"); }

11 #include //matrix multiplier using namespace std; int main() { int rows_a = 3, rows_b = 3, cols_a = 3, cols_b = 2; int a[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, {7, 8, 9 } }; int b[3][2] = { { 1, 2 }, {3, 4}, {5, 6} }; int c[3][2]; for (int i = 0; i < rows_a; i++) { for (int j = 0; j < cols_b; j++) { int sum = 0; for (int k = 0; k < cols_a; k++) sum += (a[i][k] * b[k][j]); c[i][j] = sum; cout << "c[ " << i << " ][ " << j << " ] = " << c[i][j] << endl; } system("pause"); }

12 Array int array[5]={1,3,4,2,7}; Or can be written int array[]={1,3,4,2,7}; Not expressions array [0] = a; array [a] = 75; b = array [a+2]; array [array [a]] = array [2] + 5;

13 // arrays example #include using namespace std; int m[] = {16, 2, 77, 40, 12071}; int i,sum=0; int main () { for ( i=0 ; i<5 ; i++ ) { sum+= m[i]; } cout <<sum; return 0; }

14 int a[3][5]; int a[3][5]={{1,2,3,4,5},{2,4,6,8,10},{3,6,9,1 2,15}}; int a[3][5]={{1,3,4,5},{10},{12,15}}; All is zero

15 arrays as parameters // #include using namespace std; void printarray(int arg[], int length) { for (int n=0; n<length; n++) cout << arg[n] << " "; cout << "\n"; } int main () { int firstarray[] = {5, 10, 15}; int secondarray[] = {2, 4, 6, 8, 10}; printarray (firstarray,3); printarray (secondarray,5); return 0; }

16 //Print array and sum of all #include using namespace std; int main() { int A[]={5,6,1,9,12,4,7}; int sum=0; for(int i=0;i<7;i++) { cout<<A[i]<<" "; sum+=A[i]; //sum =sum+A[i]; } cout<<"\nsum= "<<sum<<endl; return 0; }

17 // program to add matrix to another one #include using namespace std; int main() { int a[10][10],b[10][10],c[10][10]; int i,j,m,n; cout >m; cout >n; for(i=0;i<m;i++) for(j=0;j<n;j++) { cout >a[i][j]; cout >b[i][j]; c[i][j]=a[i][j]+b[i][j]; } for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<a[i][j]<<" "; cout<<"\n"; } cout<<"\n +\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<b[i][j]<<" "; cout<<"\n"; } cout<<"\n =\n\n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cout<<c[i][j]<<" "; cout<<"\n"; } return 0; }

18 18 Input from a data file Arrays are often used to store information from a data file int k; double time[10], motion[10]; FILE *sensor3; sensor3 = fopen(“sensor3.dat”, “r”); for(k=0; k<10; k++) { fscanf(sensor3, “%lf %lf”, &time[k], &motion[k]); }

19 19 Exercise Show the contents of the arrays defined in each of the following sets of statements. int x[10] = {-5, 4, 3}; char letters[] = {'a', 'b', 'c'}; double z[4];

20 20 Exercise int data[100], i; Store random numbers [0,99] in data for (i=0; i<100; i++) data[i] = rand() % 100; Store random numbers [10,109] in data for (i=0; i<100; i++) data[i] = (rand() % 100) + 10; OR for (i=0; i<100; i++) data[i] = rand_int(10,109);

21 21 Computations on one-D arrays

22 22 Find Maximum Find maximum value in data array int data[100], max, i; for (i=0; i<100; i++) data[i] = rand_int(10,109); max = data[0]; for (i=1; i<100; i++){ if (data[i] > max) max = data[i]; } printf("Max = %d\n",max);

23 23 Find average Find average of values in data array int data[100], sum, i, avg; for (i=0; i<100; i++) data[i] = rand_int(10,109) ; sum = 0; for (i=0; i<100; i++){ sum = sum + data[i]; } avg = (double)sum/100; printf(“Avg = %lf\n", avg);

24 24 Number of elements greater than average After finding the average as shown in previous slide, use the following code count = 0; for (i=0; i<100; i++){ if (data[i] > avg) count++; } printf(“%d elements are “ “greater than avg”, count);

25 25 Find pair sum Find sum of every pair in data and write into pair array data[0]=5 data[1]=7 data[2]=15 data[3]=5 … … data[98]=3 data[99]=12 pair[0]=12 pair[1]=20 … pair[49]=15 } } }......

26 26 solution int data[100], pair[50], i; for (i=0; i<100; i++) data[i] = rand_int(1,100); for (i=0; i<50; i++){ pair[i]= data[2*i] + data[2*i+1]; }

27 27 Randomly re-shuffle numbers 30 times data[0]=5 data[1]=7 data[2]=15 data[3]=5 … … data[98]=3 data[99]=12...... data[0]=12 data[1]=7 data[2]=5 data[3]=15 … … data[98]=3 data[99]=5

28 28 solution int data[100], i, j, k, tmp; for (i=0; i<100; i++) data[i] = rand_int(1,109); for (n=0; n<30; n++){ i=rand_int(0,99); j=rand_int(0,99); tmp = data[i]; data[i] = data[j]; data[j] = tmp; }

29 29 Copy array1 to array2 in reverse order 631972 021345 279136 array1 array2

30 30 Print sum of top-bottom pairs A[0]=3 A[1]=6 … A[49]=5 A[50]=3 A[98]=4 A[99]=5 +++ ….

31 31 Random numbers from an irregular range Suppose you want to generate 50 random numbers, but you want to chose them uniformly from a set of given numbers like 52 67 80 87 90 95 Can you do this using arrays?

32 32 Group avg Suppose we have a sorted array of hundred grades. We want to find the average of top ten, second top ten students etc. Grade[0] Grade[1] …. Grade[9] Grade[10] … Grade[19] Grade[20] … Grade[90] …. Grade[99] } } }

33 33 Lecture++; NameAddrContent Lecture20 REVIEW

34 34 Lecture++; NameAddrContent Lecture21 MIDTERM 2

35 35 Lecture++; NameAddrContent Lecture22

36 36 Arrays as Function Arguments

37 37 Function Arguments Individual elements of an array can be passed as regular arguments. void donothing(int a, int b) { … } int main(void) { /* Declare variables and functions */ int array[5] = {1,2,3,4,5}; donothing(array[2], array[4]); } Calls donothing(3, 5);

38 38 Passing Arrays to Functions Arrays are always pass by reference Modifications to the array are reflected to main program The array name is the address of the first element The maximum size of the array must be specified at the time the array is declared. The actual number of array elements that are used will vary, so the actual size of the array is usually passed as another argument to the function

39 39 main() { int a[2]={3, 5}; int c; c = sum_arr(a, 2) } int sum_arr(int b[], int n) { int i, sum=0; for(i=0; i < n; i++) sum = sum + b[i]; return(sum); } a[0]=3 a[1]=5 c=? 8 b= n=2 i=0 1 2 sum=0 3 8 Exercise

40 40 main() { int a[2]={3, 5}; int c; c = sum_arr(a, 2) } int sum_arr(int b[], int n) { int i, sum=0; for(i=0; i < n; i++) sum = sum + b[i]; b[0] = 20; return(sum); } a[0]=3 20 a[1]=5 c=? 8 b= n=2 i=0 1 2 sum=0 3 8 Exercise

41 41 Exercise int maximum(int fdata[], int n) { int i, fmax; fmax = fdata[0]; for (i=0; i<n; i++) if(fdata[i] > fmax) fmax = fdata[i]; return(fmax); } Write a function to find maximum value in the array data int main() { int data[100],i, max; for (i=0; i<100; i++) data[i] = rand() % 100; max = maximum(data,100); printf("Max = %d\n",max); return(0); }

42 42 Exercise void print(int pdata[], int n) { int i; for (i=0; i<n; i++) printf("data[%d]=%d\n", i,pdata[i]); return; } void modify(int fdata[], int n) { int i; for (i=0; i<n; i++) fdata[i] = 1; return; } What is the output of the following program? int main() { int data[10]; for (i=0; i<10; i++) data[i] = rand() % 100; print(data,10); modify(data,10); print(data,10); return(0); }

43 43 Skip Study 5.2, 5.3, and 5.5 from the textbook. We will go over section 5.4 Statistical measurements in class

44 44 5.4 Statistical measurements In engineering, analyzing the statistical characteristics of data is important Suppose we have an array of measurements (double data) Let us develop functions to compute max, min, mean (average), median, variance, std-dev of these measurements

45 45 max() and min() double max(double x[], int n) { /* Declare variables. */ int k; double max_x; /* Determine maximum value in the array. */ max_x = x[0]; for (k=1; k <= n-1; k++) if (x[k] > max_x) max_x = x[k]; /* Return maximum value.*/ return max_x; } double min(double x[], int n) { /* Declare variables. */ int k; double min_x; /* Determine minimum value in the array. */ min_x = x[0]; for (k=1; k < n; k++) if (x[k] < min_x) min_x = x[k]; /* Return minimum value.*/ return min_x; }

46 46 mean() double mean(double x[], int n) { /* Declare variables. */ int k; double sum; /* Determine sum of values in the array. */ sum = x[0]; for (k=1; k<=n-1; k++) sum = sum + x[k]; /* Return avg value. */ return sum/n; }

47 47 median() /* values in x must be sorted ! */ double median(double x[], int n) { /* Declare variables. */ int k; double median_x; /* Determine median of values in the array. */ k = floor(n/2); if( n % 2 != 0) median_x = x[k]; else median_x = (x[k-1]+x[k])/2; /* Return median value. */ return median_x; } Example: x[]={7, 9, 15, 27, 29}; n=5; median_x=15 x[]={3, 6, 7, 9}; n=4; median_x=(6+7)/2 median_x=6.5

48 48 variance() double variance(double x[], int n) { /* Declare variables. */ int k; double mu, sum=0; mu = mean(x, n); for (k=0; k<=n-1; k++) sum = sum + pow(x[k]-mu, 2); /* Return variance value. */ return sum/(n-1); }

49 49 std_dev() double std_dev(double x[], int n) { /* Return standard deviation */ return sqrt(variance(x, n)); }

50 50 Lecture++; NameAddrContent Lecture23

51 51 5.6 Sorting an array 631972 021345 123679136972126973 123976 123679

52 52 Selection Sort (solution 1) void selection_sort(double x[], int n) { int k,j,m; double temp; for(k=0; k<=n-2; k++){ m = k; for(j=m+1; j<=n-1; j++) if(x[j] < x[m]) m = j; temp = x[k]; x[k] = x[m]; x[m] = temp } m = find_min_pos(x, n, k); swap(x, k, m);

53 53 Selection Sort (solution 2) void selection_sort(double x[], int n) { int k, m; for(k=0; k<=n-2; k++){ m = find_min_pos(x, n, k); swap(x, k, m); }

54 54 Selection Sort cont’d int find_min_pos(double fx[], int fn, int fk) { int j; int m=fk; for (j=m+1; i<=fn-1; j++) if (fx[j] < fx[m]) m = j; return(m); }

55 55 Selection Sort cont’d void swap(double sx[], int sk, int sm) { double temp; temp = sx[sk]; sx[sk] = sx[sm]; sx[sm] = temp; return; }

56 56 Reverse an array 631972 021345 279136

57 57 Reverse an Array void reverse(double x[], int n) { int i=0, j=n-1; while (i<j) { swap(x,i,j); i = i + 1; j = j - 1; } return; }

58 58 Merge two sorted array Assume we have A and B arrays containing sorted numbers For example A = { 3, 5, 7, 9, 12} B = {4, 5, 10} Merge these two arrays as a single sorted array C, for example C = {3, 4, 5, 5, 7, 9, 10, 12}

59 59 5.7 Search Algorithms Unordered list Linear search In a loop compare each element in array with the value you are looking for (  ) Ordered list Linear search A better solution is known as Binary search (but we will skip it this time, it is like looking for a word in a dictionary)

60 60 Unordered list – linear search int search1(int x[], int n, int value) { int i; for(i=0; i < n; i++) { if (x[i]== value) return i; } return(-1); }

61 61 Ordered list – linear search int search2(int x[], int n, int value) { int i; for(i=0; i < n; i++) { if (x[i]== value) return i; else if (x[i] > value) break; } return(-1); }

62 62 Lecture++; NameAddrContent Lecture24

63 63 Strings (strings are discussed in Section 6.6 of the textbook ) A string is an array of characters char data[10] = “Hello”; char data2[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’} Use printf to print strings printf(“%s”,data); Can be accessed char by char data[0] is first character Hello\0 0 1 2 3 4 5 6 7 8 9 data End of String Symbol

64 64 Each character has an integer representation Strings abcdez………… 97 98 99 100 101 ………………………112 ABCDEZ………… 65 66 67 68 69 ……………………… 90 0123498765 48 49 50 51 52 53 54 55 56 57 \0 0 \n 10

65 65 Characters can be interpreted as integers char c = ‘A’; printf(“%c \n”,c); prints A printf(“%d \n”,c); prints 65 Printf(“%c \n”,65); prints A Strings

66 66 Exercise Write a function to count the number of characters in a string. Idea: count the number of characters before \0 Hello\0

67 67 Solution int count_letters(char cdata[]) { int i=0; while (cdata[i] != '\0') i = i + 1; return(i); }

68 68 Exercise Write a function that prints a string in reverse Idea: find the end of the string and print the characters backwards. Hello\0 Output: olleH

69 69 Solution void print_reverse(char pdata[]) { int size,position; size = count_letters(pdata); position = size - 1; while (position >= 0) { printf("%c",pdata[position]); position = position -1; } printf("\n"); return; }

70 70 Exercise Write a function that compares 2 strings S1 and S2 using lexicographic order. Idea: compare character by character Return a neg value if S1 < S2, 0 if S1 == S2 a pos value if S1 > S2 Hello\0 Heloo l < o in lexicographic order

71 71 Solution (incomplete) int compare(char cdata1[], char cdata2[]) { int i= 0; while (cdata1[i] == cdata2[i]) i = i + 1; return (cdata1[i] - cdata2[i]); }

72 72 Solution (complete) int compare(char cdata1[], char cdata2[]) { int i= 0; while (cdata1[i] != ‘\0’ && cdata2[i] != ‘\0’ && cdata1[i] == cdata2[i]) i = i + 1; return (cdata1[i] - cdata2[i]); }

73 73 Exercise: Spell out a number in text using arrays of strings Write a program that reads a number between 1 and 999 from user and spells out it in English. For example: 453  Four hundred fifty three 37  Thirty seven 204  Two hundred four

74 74 Lecture++; NameAddrContent Lecture25

75 75 More Examples of one dimensional arrays

76 76 Trace a program Trace the following program and show how variables change in memory. int main() { int x[5]={3, 5, 3, 4, 5}; int i, j, count; for(i = 0; i < 5; i++){ count = 1; for(j = i+1; j < 5; j++){ if (x[i] == x[j]) count++; } printf(“%d %d \n”, x[i], count); } x[0]3 x[1]5 x[2]3 x[3]4 x[4]5 i? j? count?

77 77 int find_count(int cdata[], int n, int x) { int count = 0; int i; for (i = 0; i<n; i++){ if (cdata[i] == x) count = count + 1; } return (count); } Count how many times a value appears in the array find_count(A,6,2) returns 1 find_count(A,4,2) returns 0 631972 0 123 45

78 78 Insert unique RNs Insert random numbers into an array so that each number appears in the array at most once. int A[6]; for (i=0; i<6; i++) A[i] = rand() % 10; Produces Duplicates 631962 A

79 79 Insert unique RNs (cont’s) Insert random numbers into an array so that each number appears in the array at most once. void initialize(int idata[], int n) { int i=0, j, elem; while (i<=n) { elem = rand() % 10; if (find_count(idata,i,elem) == 0) { idata[i] = elem; i = i + 1; } 63196 A Try a new number

80 80 Intersection Set Suppose we have two sets (groups) represented by A and B E.g., A is the set of students taking Math, B is the set of students taking Science. Find set C, the intersection of A and B, i.e., students taking both Math and Science For each element ID in A Search that ID in B if found, put ID into C 3 6 9 1 7 2 4 5 8

81 Use arrays to represent A and B Hand example 81 631972 A 425618 B 61 2 C i=0j=0 k=0 j=1j=3 k=1 i=1 j=2 k=2 i=2 i=3 k=3 j=0 j=1 j=2 j=3 j=4 j=5 j=6 j=0 j=1 j=2 j=3j=4 i=4i=5i=6

82 82 int intersection(int A[],int B[], int C[], int n) { int i=0, j=0, k=0; for(i=0; i < n; i++) { for(j=0; j < n; j++) { if (A[i]==B[j]){ C[k]=A[i]; k++; break; } return(k); } Solution 631972 425618 612

83 83 int intersection(int A[], int B[], int C[], int n) { int i=0, k=0, elem; while (i < n) { elem = A[i]; if(find_count(B,n,elem) == 1) { C[k] = elem; k = k + 1; } i = i + 1; } return(k); } Another Solution 631972 425618 612

84 What if A and B were sorted? Will the previous solution work? Yes, but we could find intersection set faster! How? See next slide 84 123679124568126

85 85 int sorted_intersection(int A[],int B[], int C[], int n) { int i=0, j=0, k=0; while( i < n && j < n ) { if (A[i]==B[j]){ C[k]=A[i]; k++; i++; j++; } else if (A[i] < B[j]) { i++; } else { /* A[i] > B[j] */ j++; } return(k); }

86 86 Exercise: union or difference As in previous example suppose two sets are given as arrays. Find union and difference For example A={3,4,5} and B={2,3,5,7} A U B = {2,3,4,5,7} A – B = {4} B – A = {2,7}

87 87 Exercise: Histogram Suppose somehow we read npts integer numbers from a file into an array declared by int x[100]. We know that all the values are integers between 0 and 10. Now suppose we want to find how many 0’s,1’s, …, 10’s exist in the array x. Write a function that will take x and npts as the parameters and prints out the number of 0’s,1’s, …, 10’s that exist in the array x

88 88 solution void my_function(int x[], int npt) { int i, hist[11]={0}; for(i=0; i < npt; i++) hist[x[i]]++; for(i=0; i < 11; i++) printf(“%d appears %d times\n”, i, hist[i]); return; }

89 89 Number of Even values in a given range Suppose somehow we read 100 values from a file into an array declared by int x[100]. We are now interested in finding the number of even values in x that are happen to be in a given range, say int Low=22, High=53. Write a function that will take x, Low, High as parameters and return the number of even values in x that are happen to be between Low and High.

90 90 Exercise: strings (char array) Write a function to check if v=“abcd” appears in a given string A?

91 91 Lecture++; NameAddrContent Lecture26

92 92 5.8 Matrices (2D-array) A matrix is a set of numbers arranged in a grid with rows and columns. A matrix is defined using a type declaration statement. datatype array_name[row_size][column_size]; int matrix[3][4]; in memory Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 4 1 0 2 2 4 3 0 3 1 4102 243 0 31

93 93 Accessing Array Elements int matrix[3][4]; matrix has 12 integer elements matrix[0][0] element in first row, first column matrix[2][3] element in last row, last column matrix is the address of the first element matrix[1] is the address of the Row 1 matrix[1] is a one dimensional array (Row 1)

94 94 Initialization int x[4][4] = {{2, 3, 7, 2}, {7, 4, 5, 9}, {5, 1, 6, -3}, {2, 5, -1, 3}}; int x[][4] = {{2, 3, 7, 2}, {7, 4, 5, 9}, {5, 1, 6, -3}, {2, 5, -1, 3}};

95 95 Initialization int i, j, matrix[3][4]; for (i=0; i<3; i++) for (j=0; j<4; j++) matrix[i][j] = i; j 0 1 2 3 0 1 2 i 0000 1111 2222 j 0 1 2 i 0123 0123 0123 matrix[i][j] = j;

96 96 Exercise 012 123 234 345 Write the nested loop to initialize a 2D array as follow int i, j, x[4][3]; for(i=0; i<4; i++) for(j=0; j<3; j++) x[i][j] = i+j;

97 97 2-Dim Arrays as Arguments to Functions void print_m(int m[][ 4 ], int r, int c) { int i,j; for (i=0; i < r; i++) { for (j=0; j < c; j++) printf("%.5d ",m[i][j]); printf("\n"); } printf("\n"); return; } int i, j, matrix[3][4]; for (i=0; i<3; i++) for (j=0; j<4; j++) matrix[i][j] = i; print_m(matrix, 3, 4); void print_m(int m[3][ 4 ], int r, int c)

98 98 Computations on 2D arrays

99 99 Max in 2D Find the maximum of int matrix[3][4] 0 120 243 0 31 0 1 2 3 0 1 2 int max = matrix[0][0]; for (i=0; i<3; i++) for (j=0; j<4; j++) if (matrix[i][j] > max) max = matrix[i][j];

100 100 Find a value in 2D Find the number of times x appears in int matrix[3][4] 0 120 243 0 31 0 1 2 3 0 1 2 int count = 0; for (i=0; i<3; i++) for (j=0; j<4; j++) if (matrix[i][j] == x) count = count + 1;

101 101 Matrix sum Compute the addition of two matrices 3 033 0663 2044 0 1 2 3 0 1 2 0 120 243 0 31 0 1 2 0 1 2 3 + 3 13 1420 2113 0 1 2 0 1 2 3 =

102 102 solution int matrix1[3][4], matrix2[3][4], sum[3][4]; // initialize matrix1 and matrix2 for (i=0; i<3; i++) for (j=0; j<4; j++) sum[i][j]= matrix1[i][j]+matrix2[i][j];

103 Exchange Two Rows 103 462 053 081 214 462 214 081 053

104 104 Transpose void transpose(int a[NROWS][NCOLS], int b[NCOLS][NROWS]) { /* Declare Variables. */ int i, j; /* Transfer values to the transpose matrix. */ for(i=0; i<NROWS; i++){ for(j=0; j<NCOLS; j++) { b[j][i] = a[i][j]; } } return; } 153 426 14 52 36 b a

105 105 mine sweeper If m[i][j] is 0, there is no mine in cell m[i][j] If m[i][j] is 1, there is a mine in cell m[i][j] Print the number of mines around cell m[i][j] [i][j]

106 106 Solution (1) - incomplete count=0; if( m[i-1][j-1]) count++; if( m[i-1][j] ) count++; if( m[i-1][j+1]) count++; if( m[i][j-1])count++; if( m[i][j+1]) count++; if( m[i+1][j-1]) count++; if( m[i+1][j] ) count++; if( m[i+1][j+1]) count++;

107 107 What if [i][j] is not in the middle? [i][j]

108 108 Solution (1) – complete NR: is number of rows NC: number of columns count=0; if( i>0 && j>0 && m[i-1][j-1]) count++; if( i>0 && m[i-1][j] ) count++; if( i>0 && j<NC-1 && m[i-1][j+1]) count++; if( j>0 && m[i][j-1]) count++; if( j<NC-1 && m[i][j+1]) count++; if( i 0 && m[i+1][j-1]) count++; if( i<NR-1 && m[i+1][j] ) count++; if( i<NR-1 && j<NC-1 && m[i+1][j+1]) count++;

109 109 Solution (2) NR: is number of rows, NC: number of columns int r, c, count=0; for(r=i-1; r <= i+1; r++) { if (r = NR) continue; for(c=j-1; c <= j+1; c++) { if (c = NR) continue; if (c == c) continue; if( m[r][c]) count++; }

110 110 Example: Resize a picture A b&w picture is usually represented using a two-dimensional array, where each element (called pixel) of the array is an integer number denoting the intensity of the light at a given pixel. Suppose we have a b&w picture with the size of 100x200 pixels and we want to reduce its size to 50x100 pixels. For this, we may consider 4 pixels from the original picture and take their average to create one pixel in the new picture. For example: 4x6 original picture can be reduced to 2x3 resized picture Write a function that takes orig[100][200] and resized[50][100] as parameters and determines the values in resized picture as described above. 453210 616123 210 62 431 5

111 111 Matrix multiplication double a[3][2], b[2][4], c[3][4]; Find c = a * b; x = 3*2 + 4*4=223*3 + 4*5=29 2371 4568 34 52 16 22294535 18404721 26334349 5*2 + 2*4=18 3*7 + 4*6=45 3*1 + 4*8=35 5*3 + 2*5=40 5*7 + 2*6=475*1 + 2*8=21 1*2 + 6*4=261*3 + 6*5=331*7 + 6*6=431*1 + 6*8=49

112 112 Matrix Multiplication cont’d x = 2371 4568 34 52 16 22294535 18404721 26334349 i=0 i j j 34 2 4 x j=0 k k = c[i][j] = a[i][k=0]*b[k=0][j] + a[i][k=1]*b[k=1][j] 0 1 2 3 i 012012 012012

113 113 Matrix Multiplication cont’d #define N 3 #define M 2 #define L 4 void matrix_mul(a[N][M], int b[M][L], int c[N][L]) { int i, j, k; for(i=0; i < N; i++) { for(j=0; j < L; j++) { c[i][j] = 0; for(k=0; k < M; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } return; }

114 Exercise: Find possible values for cell s[i][j] in Sudoku 114 41768 8437 534 741 319[i][j]746 689 357 8269 45183

115 Exercise: Dynamic programming 115 012345 1 2 3 A[i][j] = max{A[i-1][j-1], A[i-1][j]+A[i][j-1]} + max

116 116 Exercise: Walks on 2d Arrays write a code to print the values in the given order xxx xx xxx xx xx x

117 117 Example: Closest Points Suppose somewhat we read 100 points in a 2-dimentional space (each point is represented by (x,y)) and we store these points in an array declared by double p[100][2] (you can think that p[i][0] is the x value and p[i][1] is the y value of ith point). We are now interested in finding the closest two points. For example, if p[3][2] = {{1,1}, {2,1}, {1,3} }; Then we will say that points (1,1) and (2,1) are the closest two points. Write a function that takes p[100][2] as a parameter and prints out the closest two points. Suppose you have the following function: double distance (double p1[ ], double p2[ ]) { return sqrt( (p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1])); } 12 1 2 3

118 118 Skip Study Section 5.9 (terrain navigation) Study Section 5.10* Study Section 5.11* (optional) Study Section 5.12* (optional) Study Section 5.13* (optional)


Download ppt "1 5.1 One-Dimensional Arrays Suppose, you need to store years of 100 cars. Will you define 100 variables? int y1, y2,…, y100; An array is an indexed data."

Similar presentations


Ads by Google