280 likes | 502 Views
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings. Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05). Homework. Read Chapter 6 The project has been posted. HW5 is due next week and helps you start the project.
E N D
Beginning C for EngineersFall 2005Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Homework • Read Chapter 6 • The project has been posted. • HW5 is due next week and helps you start the project. • Exam Study (Question and Answer) Session for both Sections: • Monday October 10 in DCC 330 starting at 8pm
Declare variables to store and add 3 temperatures int temp1, temp2, temp3; int total; 4000 4002 4004 4006 total temp1 temp2 temp3 scanf(“%d %d %d”, &temp1, &temp3, &temp3); total = temp1 + temp2 + temp3;
5000 5002 5004 5006 . . . . temp[0] temp[1] temp[2] . . . . temp[999] What if you wanted to store and total 1000 temperatures? int temps[ 1000 ] ; /*declares an array of 1000 int values */
Array Definition An array is a structured collection of components (called array elements), all of the same data type, given a single name, and stored in adjacent memory locations. The individual components are accessed by using the array name together with an integer valued index in square brackets. The index indicates the position of the component within the collection (starts at 0, not 1).
Another Example • Declare an array called scores which will hold up to 5 test scores. float scores[5]; /* declaration allocates memory */ number of elements in the array Base Address 7000 7004 7008 7012 7016 scores[0] scores[1] scores[2] scores[3] scores[4] indexes or subscripts
Assigning Values to Individual Array Elements float temps[ 5 ] ;/* allocates memory for array */ int m = 4 ; temps[ 2 ] = 98.6 ; temps[ 3 ] = 101.2 ; temps[ 0 ] = 99.4 ; temps[ m ] = temps[ 3 ] / 2.0 ; temps[ 1 ] = temps[ 3 ] - 1.2 ;/* what value is assigned?*/ 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6 temps[0] temps[1] temps[2] temps[3] temps[4]
What values are assigned? float temps[ 5 ] ;/* allocates memory for array */ int m ; for (m = 0; m < 5; m++) { temps[ m ] = 100.0 + m *0.2 ; } 7000 7004 7008 7012 7016 ? ? ? ? ? temps[0] temps[1] temps[2] temps[3] temps[4]
Now what values are printed? float temps[ 5 ] ;/* allocates memory for array */ int m ; . . . . . for (m = 4; m >= 0; m-- ) { printf(“%f\n”, temps[ m ]); } 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8 temps[0] temps[1] temps[2] temps[3] temps[4]
6000 6002 6004 6006 6008 40 13 20 19 36 ages[0] ages[1] ages[2] ages[3] ages[4] Initializing in a Declaration int ages[ 5 ] = { 40, 13, 20, 19, 36 } ; int m; for ( m = 0; m < 5; m++ ) { printf( “%f\n”, ages[ m ]) ; }
Copying Arrays • You cannotassign arrays with = int mylist[100], yourlist[100]; … mylist = yourlist; /* WRONG! */ • Instead, you must copy each element: for (i = 0; i < 100; i++) mylist[i] = yourlist[i];
Character strings represented as char Arrays char name[10] = “Bettina”; // allocates 10 chars • A character string always ends with a ‘\0’ (the null character, a byte with all 0’s) • Therefore you can only store 9 chars + ‘\0’ in a 10 character array.
Assigning Values to Character Strings#include <string.h> • You can initialize a string with = when you declare it char name[10] = “Bettina”; • You cannot assign a string with = after it’s been declared name = “Bettina”; /* WRONG! */ • Instead, use the strcpy function to copy a value to a variable. strcpy (variable, value); strcpy(name, “Bettina”);
More Operations on Character Strings#include <string.h> char name[10]; Assignment- Use strcpy(dest, source); strcpy(name, “Bettina”); /*Note: Can’t use name = “Bettina”; */ Comparing- Use strcmp(name, “Bettina”); /* Can’t use == */ - strcmp returns 0 if name == “Bettina” - something less than 0 ifname is less than “Bettina”, and something greater than 0 if name is greater than “Bettina”. (alphabetical order & cap letters are greater than lower case) Concatenating - Use strcat(str1, str2); - combines two strings so new string is str1 followed by str2 strcat(name, “ Schimanski”); /* name is now “Bettina Schimanski” */
Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information as arguments: • the array itself • the number of elements to process in the array
Passing Arrays as Arguments • Normally, if you change the value of a parameter in a function it doesn’t affect the argument. (pass by value) Ex: int main( ) { … fun(x); … } • However, in C, arrays are passed by reference, so changes made to the parameter array are reflected in the argument int main( ) { int x[5]; fun(x, 5); … } void fun(int a) { /* doesn’t change x */ a = 10; } void fun(int y[ ], int size) { /* changes x in main */ y[1] = 10; }
Example with Array Parameters /* Get num integers into myarray */ void Read ( int myarray[ ], int num) { int i; for (i = 0; i < num; i++) { printf( “Enter a number: “); scanf(“%d”, &myarray[i]); } } This changes the elements in the array, so that the changes are seen when you use the array in main or other functions (even though the function Read does not return anything)
Function Calls with Arrays You only need to pass it the name of the array. You don’t use square brackets. int myarray[100]; Read(myarray, 100); No [ ] needed
More about Array Index • it is the programmer’s responsibility to make sure that an array index does not go out of bounds. The index must be within the range 0 through the declared array size minus one. (i.e. int myarray[10] - index must be in range 0 – 9) • using an index value outside this range causes the program to access memory locations outside the array. The index value determines which memory location is used.
Two-Dimensional Array is a collection of components, all of the same type,structured in two dimensions, (referred to as rows and columns). Individual components are accessed by a pair of indexes representing the component’s position in each dimension. SYNTAX FOR ARRAY DECLARATION DataType ArrayName [ConstIntExpr] [ConstIntExpr] ;
Must be const or use integers directly EXAMPLE -- To keep monthly high temperatures for all 50 states in one array. const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; … int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; [ 0 ] [ 1 ] [ 2 ] . . . [ 48 ] [ 49 ] [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 66 64 72 78 85 90 99 105 98 90 88 80 row 2, col 7 might be Arizona’s high for August stateHighs[2][7]
Looping through a 2-D array:Use Nested loops • The outer loop should be the rows, the inner loop the columns const int NUM_STATES = 50 ; const int NUM_MONTHS = 12 ; … int stateHighs [ NUM_STATES ] [ NUM_MONTHS ] ; for (rows = 0; rows < NUM_STATES; rows++) for (cols = 0; cols < NUM_MONTHS; cols++) scanf (“%d”, &stateHighs[rows][cols]);
Consider the following input with the number of votes received by three candidates District Candidate A Candidate B Candidate C 0 402 717 312 1 999 1420 222 2 200 404 612 3 222 914 980 How would you read them in to an array called votes? const int num_districts = const int num_candidates = int votes [ num_districts ] [ num_candidates ] ; for (rows = 0; rows < num_districts; rows++) for (cols = 0; cols < num_candidates; cols++) scanf (“%d”, &votes[rows][cols]); 4; 3;
Summing rows and columns const int num_districts = 4; const int num_candidates = 3; int votes[num_districts][num_candidates]; … /* Sum district votes for one state */ int districtSums[num_districts]; for (d = 0; d < num_districts; d++) { districtSums[d] = 0; for (c = 0; c < num_candidates; c++) districtSums[d] += votes[d][c]; }
Summing rows and columns (cont.) const int num_districts = 4; const int num_candidates = 3; int votes[num_districts][num_candidates]; … /* Sum candidate votes for one state */ int candidateSums[num_candidates]; for (c = 0; c < num_candidates; c++) { candidateSums[c] = 0; for (d = 0; d< num_districts; d++) candidateSums[c] += votes[d][c]; }
Arrays as Parameters • just as with a one-dimensional array, when a two- (or higher) dimensional array is passed as an argument, any changes made to the array in the function are reflected in main (or wherever the function was called from) • the size of all dimensions except the first must be included in the function heading and prototype • the sizes of those dimensions in the function’s parameter list must be exactly the same as declared for the caller’s array
void clearArray (int stateHighs [ ] [ NUM_MONTHS] ) /* Clears the array for high temps, setting all values to 0 */ { int state; int month; int total; for ( state = 0 ; state < NUM_STATES; state++ ) { for (month = 0 ; month < NUM_MONTHS ; month++) stateHighs[state][month] = 0; } } /* NUM_MONTHS and NUM_STATES were declared as global variables */
Labs and the Project • Today’s Lab, as usual, is due by 11:59pm tomorrow if not finished in class today • HW 5 (start project) • Already posted on the web