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.

Slides:



Advertisements
Similar presentations
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Advertisements

Computer Programming w/ Eng. Applications
1 Various Methods of Populating Arrays Randomly generated integers.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
Need for Arrays Exercise Read the IDs and the grades for all ICS 101 students. Compute and print the average of the students. Print the grades and IDs.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT5: Array (1D and 2D) CS2311 Computer Programming.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Introduction to Arrays.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
CHAPTER 11 Space and Time Complexity in Chapter 1 All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
 2007 Pearson Education, Inc. All rights reserved C Arrays.
CHAPTER 1 BASIC CONCEPT All the programs in this file are selected from Ellis Horowitz, Sartaj Sahni, and Susan Anderson-Freed “Fundamentals of Data Structures.
Programming Arrays. Question Write a program that reads 3 numbers from the user and print them in ascending order. How many variables do we need to store.
1 Arrays and Matrices Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Copyright © 2012 Pearson Education, Inc. Chapter 8 Two Dimensional Arrays.
1 1-d Arrays. 2 Array Many applications require multiple data items that have common characteristics  In mathematics, we often express such groups of.
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Arrays ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
A.Abhari CPS1251 Multidimensional Arrays Multidimensional array is the array with two or more dimensions. For example: char box [3] [3] defines a two-dimensional.
Chapter 8 Arrays and Strings
1 Programming with Pointers Turgay Korkmaz Office: SB Phone: (210) Fax: (210) web:
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Two-Dimensional Arrays ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
Computer Programming for Engineers
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
© Janice Regan, CMPT 128, January CMPT 128: Introduction to Computing Science for Engineering Students Introduction to Arrays.
Arrays and Matrices. One-Dimensional Arrays An array is an indexed data structure All variables stored in an array are of the same data type An element.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Arrays. Arrays are objects that help us organize large amounts of information.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
1 Midterm 1 Review. 2 Midterm 1 on Friday February 27 Closed book, closed notes No computer can be used 50 minutes 4 or 5 questions write full programs.
1 Agenda Arrays: Definition Memory Examples Passing arrays to functions Multi dimensional arrays.
1 Two-Dimensional Arrays. 2 Terminology Two-dimensional arrays represent matrices A matrix contains a number of values of the same data type The values.
Objectives You should be able to describe: One-Dimensional Arrays
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
1-d Arrays.
2-D Array.
Lecture 7 Arrays 1. Concept of arrays Array and pointers
Chapter 5 Arrays and Matrices
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Array 9/8/2018.
Two Dimensional Arrays
Lecture Arrays.
Array Problem Solving & Program Design in C Eighth Edition
CNG 140 C Programming (Lecture set 8)
Lecture 10 Arrays.
Arrays and Matrices.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Presentation transcript:

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 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 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 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 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 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] list[0] list[1] list[2] list[3] list[4] OR for(i=0; i<=4; i++){ list[i] = i; }

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]

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

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

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

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

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;

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

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

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

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

// 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 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 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 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 Computations on one-D arrays

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 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 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 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 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 Randomly re-shuffle numbers 30 times data[0]=5 data[1]=7 data[2]=15 data[3]=5 … … data[98]=3 data[99]= data[0]=12 data[1]=7 data[2]=5 data[3]=15 … … data[98]=3 data[99]=5

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 Copy array1 to array2 in reverse order array1 array2

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 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 Can you do this using arrays?

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 Lecture++; NameAddrContent Lecture20 REVIEW

34 Lecture++; NameAddrContent Lecture21 MIDTERM 2

35 Lecture++; NameAddrContent Lecture22

36 Arrays as Function Arguments

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 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 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 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 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 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 Skip Study 5.2, 5.3, and 5.5 from the textbook. We will go over section 5.4 Statistical measurements in class

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 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 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 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 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 std_dev() double std_dev(double x[], int n) { /* Return standard deviation */ return sqrt(variance(x, n)); }

50 Lecture++; NameAddrContent Lecture23

Sorting an array

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 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 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 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 Reverse an array

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

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 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 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 Lecture++; NameAddrContent Lecture24

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\ data End of String Symbol

64 Each character has an integer representation Strings abcdez………… ………………………112 ABCDEZ………… ……………………… \0 0 \n 10

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 Exercise Write a function to count the number of characters in a string. Idea: count the number of characters before \0 Hello\0

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

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 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 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 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 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 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 Lecture++; NameAddrContent Lecture25

75 More Examples of one dimensional arrays

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

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 A

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; } A Try a new number

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

Use arrays to represent A and B Hand example A 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 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

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

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

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 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 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 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 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 Exercise: strings (char array) Write a function to check if v=“abcd” appears in a given string A?

91 Lecture++; NameAddrContent Lecture26

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

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 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 Initialization int i, j, matrix[3][4]; for (i=0; i<3; i++) for (j=0; j<4; j++) matrix[i][j] = i; j i j i matrix[i][j] = j;

96 Exercise 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 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 Computations on 2D arrays

99 Max in 2D Find the maximum of int matrix[3][4] 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 Find a value in 2D Find the number of times x appears in int matrix[3][4] int count = 0; for (i=0; i<3; i++) for (j=0; j<4; j++) if (matrix[i][j] == x) count = count + 1;

101 Matrix sum Compute the addition of two matrices =

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

Exchange Two Rows

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

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 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 What if [i][j] is not in the middle? [i][j]

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

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= *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 Matrix Multiplication cont’d x = i=0 i j j x j=0 k k = c[i][j] = a[i][k=0]*b[k=0][j] + a[i][k=1]*b[k=1][j] i

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

Exercise: Find possible values for cell s[i][j] in Sudoku [i][j]

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

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

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

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)