Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fall 2011GNG1106-Mod7-1 Chapter 7 Arrays Objectives: One dimensional array Two dimensional arrays Passing arrays to subprograms.

Similar presentations


Presentation on theme: "Fall 2011GNG1106-Mod7-1 Chapter 7 Arrays Objectives: One dimensional array Two dimensional arrays Passing arrays to subprograms."— Presentation transcript:

1 Fall 2011GNG1106-Mod7-1 Chapter 7 Arrays Objectives: One dimensional array Two dimensional arrays Passing arrays to subprograms

2 Fall 2011GNG1106-Mod7-2 7. Arrays We often encounter problems in engineering where a large amount of the same type of data must be manipulated (like a hundred temperature measurements, for example). –In such cases, it is inconvenient if not impossible to define a distinct variable name for each datum; it is best to use an array. An array is a data structure that can conveniently store a large amount of data of the same type. An array is a static data structure, which means that its size does not vary during the execution of the program. We can define in a computer an array of any of the basic data types available

3 Fall 2011GNG1106-Mod7-3 7.1 A one dimensional array An array is a collection of memory locations where multiple values of the same type can be stored CPU Assign 1 to arr[0] Assign 10 to arr[1] Assign 2 to ix Repeat while ix is less than 6 Assign arr[ix-1] to arr[ix] Increment ix Program Memory Working Memory arr

4 Fall 2011GNG1106-Mod7-4 The one dimensional array A one dimensional array consists of an amount of contiguous memory elements that can contain data of the same type. –The number of elements are fixed. The name of an array must be created in the same way as a variable name and using the same set of characters available for a variable name. –The name of the array corresponds to the address of the first data element in the array An element of an array is accessible by citing the name of the array followed by the element number or index in brackets []. –The name of the array with an index is equivalent to a variable name and can be used anywhere a variable name is used (e.g. expressions) –Note that expressions can be used as an index –Index values start at 0

5 Fall 2011GNG1106-Mod7-5 In C, the array consists of a name and indices are used to access its elements. In memory, a 1-D array of dimension 5, called temp and containing int ’s looks like: 7.2 One Dimensional Arrays in C 5 0 15 20 temp[0] temp[1] temp[2] temp[3] temp[4] An individual element of this array is accessed as temp[1], for example. The index, which is an integer in [] identifies the position in the array, or the element number.

6 Fall 2011GNG1106-Mod7-6 In C, the first element in an array is always element 0.  An array of 5 elements is indexed from 0 to 4,  an array of N elements is accessed using indices 0 though N-1.  Careful: the i th element is at position i-1 in the array; ie: the 4 th element is in position 3. The position of the element or the index must be an integer or an expression that evaluates to an integer. An element of an array is used in the same manner as a variable. –It can be used to the left of an assignment operator to store a value in the element. –It can be used in an arithmetic or logical expression. E.g.: temp[1] = 5 + 3; temp[1] = temp[2-1] + 1; temp[1] = temp[1] + 1; temp[0] = temp[1] / 2; temp[0] = (temp[0] <= temp[1]); The elements of an array can also be used in the arguments or function calls: E.g.: printf(“%d\n”, (temp[0]+temp[1])); scanf(“%d”, &temp[1]); 8 Temp[1] 9 10 Temp[1] 5 Temp[0] 1 Assume that temp is an array of int ’s

7 Fall 2011GNG1106-Mod7-7 An array is defined in a declaration; the declaration specifies: –the name of the array, –the type of data stored in the array, and –the size of the array (number of elements). E.g.: int temp[5]; float x[5], y[20]; The first declaration defines the array temp which contains 5 data elements of type int. The second declaration defines the arrays x and y, which contain 5 and 20 elements, respectively, of type float. The memory required to store these arrays is reserved by the compiler. 7.3 Definition and Initialization of One Dimensional Arrays

8 Fall 2011GNG1106-Mod7-8 An array can be initialized using a looping structure. E.g.: int temp[5], ctr; float x[5]; for(ctr=0; ctr<=4; ctr=ctr+1) { temp[ctr]=0; x[ctr]=(float)ctr/2; } Ctr temp[ctr] x[ctr] 0 0 0.0 1 0 0.5 2 0 1.0 3 0 1.5 4 0 2.0

9 Fall 2011GNG1106-Mod7-9 We can also initialize an array in the declaration in which it is defined. –The initial values are listed using, between {} and assigned to the array definition. E.g.: float x[5]={0.0, 0.5, 1.0, 1.5, 2.0}; After compilation, the array x contains the initial values in contiguous positions: –If there are more initial values than elements in the array, a syntax error is generated. x[0] x[1] x[2] x[3] x[4] 0.0 0.5 1.0 1.5 2.0

10 Fall 2011GNG1106-Mod7-10 –If there are less initial values than elements, then the last elements are set to zero. E.g.: int temp[5]={0}; float x[5]={0.0, 0.5, 1.0}; After compilation the arrays temp and x contain the following values: temp[0] temp[1] temp[2] temp[3] temp[4] x[0] x[1] x[2] x[3] x[4] 0000000000 0.0 0.5 1.0 0.0

11 Fall 2011GNG1106-Mod7-11 The size of an array can also be defined via the initialization list. –If the array size is not stated but the declaration contains an initialization list, then the array size is taken as being equal to the number of items in the initialization list. E.g.: int temp[]={0}; float x[]={0.0, 0.5, 1.0, 1.5, 2.0}; After compilation the arrays temp and x contain the following values: Thus temp is an array of 1 int and x is an array of 5 float ’s. –It is usually not in good style to omit the size of arrays when declaring them! temp[0]x[0] x[1] x[2] x[3] x[4] 00.0 0.5 1.0 1.5 2.0

12 Fall 2011GNG1106-Mod7-12 The use of descriptive symbolic constants in the definition of arrays and in their manipulation is strongly encouraged since they: –facilitate modifications to the program if the array size must change, and they –eliminate “magic” numbers from the program, thus rendering it more readable. E.g.: #define NBR_TEMPS 5  int temp[NBR_TEMPS], ctr; for(ctr=0; ctr <= NBR_TEMPS-1; ctr=ctr+1) temp[ctr]=0; –In the above example, if the number of temperatures to be stored must be increased from 5 to 10 then only one line of the program would need to be modified: #define NBR_TEMPS 10 –In a large program containing many arrays and loops to manipulate them, the use of symbolic constants greatly enhances the maintainability of the code.

13 Fall 2011GNG1106-Mod7-13 There is no mechanism in C to prevent a program from running over the upper and lower limits of an array during execution! –Reading or accessing an element outside of the array limits will:  generally introduce errors into the results obtained from the program, but  usually will not cause the computer to “crash” or to become “hung-up”. –Assigning a value to an element outside of the array limits will:  generally introduce errors into the results obtained from the program, and  often will cause the computer to “crash” or to become “hung-up”. The most common cause for running over the array limits is an error in the looping structure(s) used to traverse the array. Always verify that: –the index never becomes negative in value, and –that the index always remain less than or equal to the size of the array minus 1. Be consistent when writing loops that traverse an array. For example, use a symbolic constant and a logical expression similar to: for(ctr=0; ctr <= NBR_ELEMENTS-1; ctr=ctr+1) Running Over Array Limits

14 Fall 2011GNG1106-Mod7-14 Example 1 Statement of the problem –Find the minimum value in an array. (Other possible properties – the maximum value, the sum of the elements, the average of the elements, the number of times a value K is found in the array). Gathering of Information and Input/Output Description –Fill the array with a number of random values. –Find the minimum value by examining each value to see if it is smaller than any previously seen value. –Input: Minimum value, maximum value, and seed for generating random numbers. –Output: Contents of array (for array size is 10), the minimum value. Use a symbolic constant to set the size of the array to 10 and then to 10000. Complete Steps 3 and 4

15 Fall 2011GNG1106-Mod7-15 7.4 The 2 dimensional array – the matrix The 2 dimensional array, a matrix, is essentially an array of arrays –Each row in the matrix is a 1-dimensional array –The elements in the same positions of the row arrays make up the matrix columns. The matrix, like the 1-D array, occupies a contiguous memory locations –See the next slide 0 1 2 0 1 2 3 Rows Columns

16 Fall 2011GNG1106-Mod7-16 The matrix in memory CPU Assign 1 to mat[0][0] Assign 10 to mat [1][3] Assign 0 to rix Repeat while rix is less than 3 Assign 0 to cix Repeat while cix is less than 4 Assign rix+cix to mat[rix][cix] Increment cix Increment rix Program Memory Working Memory mat mat[0][0] mat[0][1] mat[0][2] mat[0][3] mat[1][0] mat[1][1] mat[1][2] mat[1][3] mat[2][0] mat[2][1] mat[2][2] mat[2][3]

17 Fall 2011GNG1106-Mod7-17 The matrix – an array of arrays The two dimensional array is often used to store data arranged in a row- column form, i.e. as matrices –Note the organization in memory – it occupies contiguous space just like the array A name (like the case of the array) is used to reference the matrix –Like the case of the array, the name corresponds to the address of the first element in the matrix The elements in a two dimensional array are accessed by citing the name of the array followed by two indices, each inserted between [] and []. –The first index specifies the row and the second index specifies the column. What do you think the name of a matrix with a single index represents? –E.g. mat[1]

18 Fall 2011GNG1106-Mod7-18 The ANSI standard for C specifies that a C compiler must support at least 12 array dimensions (this means 12 indices). A two dimensional array a of int ’s, having 3 rows and 4 columns (called a 3  4 array) is visualized as: 7.5 Two Dimensional Arrays in C col 0 col 1 col 2 col3 row 0 2 -1 11 8 row 1 0 4 -5 -9 row 2 3 10 -7 -13 Matrix a

19 Fall 2011GNG1106-Mod7-19 In C arrays are always indexed from 0 on.  The first row is row 0 and the first column is column 0. In reference to the array a of int ’s on the previous slide: element a[0][0] contains 2, element a[2][3] contains -13, element a[1][2] contains -5. An element of a two dimensional array is used in the same manner as a variable. –It can be used to the left of an assignment operator to store a value in the element. –It can be used in an arithmetic or logical expression. E.g.: a[0][0] = 5 + 3; a[2][3] = a[0][1-1] - 2; a[2][3] = a[2][3]+1; a[0][1] = a[2][3] / 2; a[0][0] = (a[0][0] <= a[0][1]); The elements of an array can also be used as an argument in a printf or a scanf : E.g.: printf(“%d\n”, a[0][0]); scanf(“%d”, &a[0][1]); 8 a[0][0] 6 a[2][3] 7 3 a[0][1] 0 a[0][0] Assume that a is an array of int ’s

20 Fall 2011GNG1106-Mod7-20 A two dimensional array is defined in a declaration; the declaration specifies: –the name of the array, –the type of data stored in the array, and –the size of the array (number of rows and number of columns). E.g.: int a[3][4]; float y[5][5]; Thus, a is defined as an array of int ’s having 3 rows and 4 columns and y is an array of float ’s having 5 rows and 5 columns. A two dimensional array can be initialized using nested loops: int a[3][4], row, col; for (row=0; row <= 2; row=row+1) for (col=0; col <= 3; col= col+1) a[row][col] = 0; –Variables of type int called i and j are also commonly used for accessing the rows and columns of a two dimensional array, respectively. 7.6 Definition and Initialization of Two Dimensional Arrays

21 Fall 2011GNG1106-Mod7-21 We can also initialize an array in the declaration in which it is defined. –The initial values are listed row-wise, where each row is grouped using {} ; the rows are then separated by commas, enclosed in {} and assigned to the array definition. E.g.: int a[3][4]={{2,-1,11,8},{0,4,-5,-9},{3,10,-7,-13}}; row 0 row 1 row 2 –If the {} delimiting the rows are omitted, then the compiler still initializes row-wise starting from the first row to the last. E.g.: int a[3][4]={2,-1,11,8,0,4,-5,-9,3,10,-7,-13}; The above stores exactly the same initial values in the array as in the previous example but it is not as readable. If values are missing in the initialization list then the missing values will be assumed zero. E.g.: int a[3][4]={0}; int a[3][4]={{2,-1,11},{0,4,-5},{3,10,-7}}; int a[3][4]={2,-1,11,8,0,4,-5,-9}; In the first case the entire array is set to zero. In the second case, the last column is set to zero. In the third case, the last row is set to zero.

22 Fall 2011GNG1106-Mod7-22 The number of rows of a two dimensional array can also be defined via the initialization list. –If the number of rows of a two dimensional array is not stated explicitly, but the declaration contains an initialization list, then the number of rows of the array is taken as being equal to the number of rows in the initialization list. E.g.: int a[][4]={{2,-1,11,8},{0,4,-5,-9},{3,10,-7,-13}}; row 0 row 1 row 2 Thus a is a two dimensional array having 3 rows and 4 columns. –It is usually not in good style to omit the number of rows when declaring a two dimensional array! The use of descriptive symbolic constants in the definition of two dimensional arrays and in their manipulation is strongly encouraged for the same reasons as in the case of the one dimensional arrays. E.g.: #define NBR_STUDENTS 3 #define NBR_TESTS 4  int a[NBR_STUDENTS][NBR_TESTS], i, j; for(i=0; i <= NBR_STUDENTS-1; i=i+1) for(j=0; j <= NBR_TESTS-1; j=i+1) a[i][j]=0;

23 Fall 2011GNG1106-Mod7-23 As in the case of a one dimensional array, good programming style and consistency when writing loops that traverse a two-dimensional array, will help avoid errors generated by going beyond the upper and lower row and column limits. For example, use symbolic constants and logical expressions similar to: for(row=0; row < NBR_ROWS; row++) for(col=0; col < NBR_COLS; col++) Traversing 2D arrays

24 Fall 2011GNG1106-Mod7-24 2 11 8 0 4 -5 -9 3 10 -7 -13 Recall the organization of Two Dimensional Arrays in Memory Two dimensional arrays are stored in contiguous memory elements. Storage is organized row-wise, beginning with the first element of the first row and ending with the last element of the last row. E.g.: int a[3][4]={{2,-1,11,8},{0,4,-5,-9},{3,10,-7,-13}}; row 0 row 1 row 2 a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] row 0 row 1 row 2 The array a is saved row-wise as 12 integers in contiguous memory locations:

25 Fall 2011GNG1106-Mod7-25 Example 2 Statement of the problem –Check a square matrix (with dimension n X n) to see if it is diagonally dominant. Information Gathering and Description of Input/Output –Engineering uses matrices, for example, they can be used to analyse the effect of earthquakes on structures (Matrix Analysis of Structural Dynamics: Applications and Earthquake Engineering, Franklin Y. Cheng, CRC Press, 2000) –A square matrix, that contains only positive integer values, is “Diagonally Dominant” when, for each row i in the matrix, the diagonal element a ii is larger than the sum of all other elements (i.e. non-diagonal) in the row. The following matrix is diagonally dominant: –Input: Dimension of the square matrix (maximum 10), m inimum value, maximum value, and seed for generating random numbers. –Output: Message that indicates if matrix is diagonally dominant. Complete Steps 3 and 4.

26 Fall 2011GNG1106-Mod7-26 7.7 Passing arrays and matrices to subprograms CPU Assign 1 to temp[0] Assign 10 to temp[1] Assign 2 to ix Repeat while ix is less than 6 Assign temp[ix-1] to temp[ix] Increment ix Assign sumArray1D(temp, 6) to theSum Print “The sum is “, theSum sumArray1D(arr, num) Assign 0 to ix Assign 0 to sum Repeat while ix is less than num Assign sum+arr[ix] to sum Increment ix Return sum Program Memory Working Memory temp arr sum ix theSum ix num

27 Fall 2011GNG1106-Mod7-27 Examine the argument list in the subprogram call. –The name of the array is cited in the argument list –What do you think is produced by evaluating this argument? –The value of the argument is the address of the array! –With arrays use pass by reference – the reference is an address. Examine the subprogram parameter list –The parameter that receives the argument is a variable that can store an address –The variable acts just like the name of the array in the caller –This means that changes made to the array in the subprogram shall be seen in the caller It is common to also pass the dimension of the array as another argument –Note that this value can actually represent the number of values in the array if the array is not full The same approach is used to pass a matrix to a subprogram –That is a name used in the argument list, which means that its address will be passed to the subprogram Passing One Dimensional Arrays to Subprograms

28 Fall 2011GNG1106-Mod7-28 The one dimensional array is passed to a function simply by citing the name of the array in the call to the function. –The array name is cited without []. –The number of elements can be included in the call if the size of the array is required by the function. –The name of the array is a reference to the array (its address). E.g.: int temp[5]={0};  sum_array_1D(temp, 5); The definition of a function that receives a one dimensional array must specify that an array will be received through its parameter list. –The passage of an array is indicated by adding [] after the name used to access the array in the function. –The brackets can be empty or may contain the number of elements in the array. E.g.: void sum_array_1D(int array_1D[], int dim) or: void sum_array_1D(int array_1D[5], int dim) 7.8 Passing Arrays as Arguments to C Functions Function call in main(). Passing One Dimensional Arrays to Functions

29 Fall 2011GNG1106-Mod7-29 The prototype of the function must also specify that an array will be received through its parameter list; this is stated in a manner similar to that found in the function header. E.g.: void sum_array_1D(int [], int); or: void sum_array_1D(int array_1D[5], int dim); Passing Two Dimensional Arrays to Functions An entire two dimensional array is passed to a function simply by citing the name of the array in the call to the function. –The array name is cited without [][]. –The number of rows and columns can be included in the call if required by the function. –The name of the matrix is a reference to the matrix. E.g.: int a[3][4]={0};  sum_array_2D(a,3,4); The definition of a function that receives a two dimensional array must specify that a two dimensional array will be received through its parameter list. –The passage of a two dimensional array is indicated by adding [][4] after the name used to access the array in the function. –The column brackets must contain the number of columns in the array. –The row brackets can be empty or may contain the number of rows in the array.

30 Fall 2011GNG1106-Mod7-30 E.g.: void sum_array_2D(int array_2D[][4], int rows, int cols) or: void sum_array_2D(int array_2D[3][4], int rows, int cols) The prototype of the function must also specify that a two dimensional array will be received through its parameter list; this is stated in a manner similar to the function definition. E.g.: void sum_array_2D(int [][4], int, int); or: void sum_array_2D(int array_2D[3][4], int rows, int cols); In C, an array is passed by reference to a function and not by value as is done with variables.  An array that is modified in a function will appear modified in the caller as well. In C, an array element is passed by value to a function as though it were a variable.  The array element can be modified in the function and this modification will not appear in the caller. On the Passage of Array Arguments to a Function

31 Fall 2011GNG1106-Mod7-31 Example 3 Go back to Example 2 Use sub-programs for the following tasks: –To get data from the user –To fill in the matrix –To print the matrix –To determine if the matrix is diagonally dominant.

32 Fall 2011GNG1106-Mod7-32 Example 4 Problem Statement –To transpose a square matrix (n X n) Gathering of Information and Description of Input/Output –Engineering uses matrices, for example, they can be used to analyze the effect of earthquakes on structures (Matrix Analysis of Structural Dynamics: Applications and Earthquake Engineering, Franklin Y. Cheng, CRC Press, 2000) –Transposing a matrix consists of moving the values in the rows into the corresponding columns. For example, if, then the transposed matrix is –Input: Dimension of the square matrix (maximum 10), m inimum value, maximum value, and seed for generating random numbers. –Output: the matrix and the transposed matrix Output: Complete Steps 3 and 4. Extra challenge: Can you figure out how to transpose the matrix without using a second matrix so that the transposed values are place in the original matrix.

33 Fall 2011GNG1106-Mod7-33 Thank You! متشکرم


Download ppt "Fall 2011GNG1106-Mod7-1 Chapter 7 Arrays Objectives: One dimensional array Two dimensional arrays Passing arrays to subprograms."

Similar presentations


Ads by Google