Download presentation
Presentation is loading. Please wait.
Published byRonald Thomas Modified over 8 years ago
1
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)
2
Homework Read Chapter 6 Read Chapter 6 The project has been posted. The project has been posted. HW5 is due next week and helps you start the project. HW5 is due next week and helps you start the project. Exam Study (Question and Answer) Session for both Sections: Exam Study (Question and Answer) Session for both Sections: Monday October 10 in DCC 330 starting at 8pm Monday October 10 in DCC 330 starting at 8pm
3
Declare variables to store and add 3 temperatures int temp1, temp2, temp3; int total; 400240004004 temp2temp1temp3 scanf(“%d %d %d”, &temp1, &temp3, &temp3); total = temp1 + temp2 + temp3; 4006 total
4
What if you wanted to store and total 1000 temperatures? int temps[ 1000 ] ; int temps[ 1000 ] ; /*declares an array of 1000 int values */ /*declares an array of 1000 int values */ temp[0] temp[1] temp[2].... temp[999] 5000 5002 5004 5006....
5
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).
6
Another Example Declare an array called which will hold up to 5 test scores. Declare an array called scores which will hold up to 5 test scores. float scores[5]; /* declaration allocates memory */ scores[0] scores[1] scores[2] scores[3] scores[4] 7000 7004 7008 7012 7016 number of elements in the array indexes or subscripts Base Address
7
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?*/ temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 99.4 ? 98.6 101.2 50.6
8
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 ; temps[ m ] = 100.0 + m 0.2 ;} temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 ? ? ? ? ?
9
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 ]); printf(“%f\n”, temps[ m ]);} temps[0] temps[1] temps[2] temps[3] temps[4] 7000 7004 7008 7012 7016 100.0 100.2 100.4 100.6 100.8
10
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 ]) ; printf( “%f\n”, ages[ m ]) ;} ages[0] ages[1] ages[2] ages[3] ages[4] 6000 6002 6004 6006 6008 40 13 20 19 36
11
Copying Arrays You assign arrays with = You cannot assign arrays with = int mylist[100], yourlist[100]; … mylist = yourlist; /* WRONG! */ Instead, you must copy each element: Instead, you must copy each element: for (i = 0; i < 100; i++) mylist[i] = yourlist[i];
12
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. ‘B’‘e’‘t’‘t’‘i’‘n’‘a’‘\0’ 0123456789
13
Assigning Values to Character Strings #include Assigning Values to Character Strings #include You can initialize a string with = when you declare it 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 You cannot assign a string with = after it’s been declared name = “Bettina”;/* WRONG! */ Instead, use the function to copy a value to a variable. strcpy (variable, value); Instead, use the strcpy function to copy a value to a variable. strcpy (variable, value); strcpy(name, “Bettina”);
14
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 if name 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” */ More Operations on Character Strings #include More Operations on Character Strings #include
15
Using Arrays as Arguments to Functions Generally, functions that work with arrays require 2 items of information as arguments: the array itself the array itself the number of elements to process in the array the number of elements to process in the array
16
Passing Arrays as Arguments Normally, if you change the value of a parameter in a function it doesn’t affect the argument. () 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); fun(x);…} However, in C, are, so changes made to the parameter array are reflected in the argument 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); 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; }
17
/* 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) Example with Array Parameters
18
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
19
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.
20
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. DataType ArrayName [ConstIntExpr] [ConstIntExpr] ; SYNTAX FOR ARRAY DECLARATION
21
[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 Must be const or use integers directly -- To keep monthly high temperatures for all 50 states in one array. 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 ] [ 0 ] [ 1 ] [ 1 ] [ 2 ] [ 2 ]... [ 48 ] [ 48 ] [ 49 ] [ 49 ] stateHighs[2][7]
22
Looping through a 2-D array: Use Nested loops The outer loop should be the rows, the inner loop the columns 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]);
23
Consider the following input with the number of votes received by three candidates District Candidate A Candidate B Candidate C 0402717312 19991420222 2200404612 3222914980 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;
24
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]; }
25
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]; }
26
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) 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 in the function heading and prototype 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 the sizes of those dimensions in the function’s parameter list must be exactly the same as declared for the caller’s array
27
void clearArray (int stateHighs [ ] [ NUM_MONTHS] ) /* Clears the array for high temps, setting all values to 0 */{ int state; int state; int month; int month; int total; int total; for ( state = 0 ; state < NUM_STATES; state++ ) for ( state = 0 ; state < NUM_STATES; state++ ) { for (month = 0 ; month < NUM_MONTHS ; month++) for (month = 0 ; month < NUM_MONTHS ; month++) stateHighs[state][month] = 0; }} /* NUM_MONTHS and NUM_STATES were declared as global variables */
28
Labs and the Project Today’s Lab, as usual, is due by 11:59pm tomorrow if not finished in class today Today’s Lab, as usual, is due by 11:59pm tomorrow if not finished in class today HW 5 (start project) HW 5 (start project) Already posted on the web Already posted on the web
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.