comp 1402
play

COMP 1402 Winter 2008 Tutorial #5 Arrays Overview of Tutorial #5 - PDF document

COMP 1402 Winter 2008 Tutorial #5 Arrays Overview of Tutorial #5 What is an array? Array syntax Character arrays Passing arrays to functions. Processing/traversing arrays Higher Dimension arrays (2d and 3d) 1 Why


  1. COMP 1402 Winter 2008 Tutorial #5 Arrays Overview of Tutorial #5 • What is an array? • Array syntax • Character arrays • Passing arrays to functions. • Processing/traversing arrays • Higher Dimension arrays (2d and 3d) 1

  2. Why do we need arrays? • Regular variables store a single value of the specified type. eg. int a; //stores a single variable of integer type • But sometimes we need several copies of a variable, such as the grades for 3 students. We could try: double grade_student1; double grade_student2; double grade_student3; //etc. • This would get very tedious if we had 100 students! What is an array? • An array is a special variable that can store many values. • In our student example instead of a separate variable for each student we could use an array of grades that keeps the grades for each student. 3 Variables student1_grade student2_grade student3_grade 87.0 75.0 91.0 A Single Array with 3 Elements grade_array 87.0 75.0 91.0 2

  3. What are arrays ... An Array Regular Variable int a[5]; int a; An array reserves a contiguous block of A regular variable memory addresses in reserves a single which we can store address in memory values of the array where its value is type (int in this case). stored. Array Syntax: Declaring • Arrays declarations have three parts, the data type, the array name and the size (number of elements), eg. int a[5]; // An array named ‘a’ which stores 5 // integer values. int a[5]; 7 • On the left we see the 13 integer array ‘a’ which a[0] = 7; 11 holds the five integer a[1] = 13; 5 values 7, 13, 11, 5, -8. a[2] = 11; a[3] = 5; -8 a[4] = -8; 3

  4. Array Elements • The elements of an array are referred to by both the array name and an 'index' value. • Index values are numbered from 0 (for the arrays first element). • The index for the last element is thus one less than the array's size. an_array 0 1 2 3 4 We would reference this element as: an_array[2] Array Syntax: Accessing Elements • An array element is accessed by supplying the array name, and the elements index inside square brackets [ ]. • We can treat each element like we would any other variable. int a[5]; // Create an array of 5 integers. a[0] = 15; // Set element 0 to the value 15 if( a[2] < 4 ) { ... } //Use elements anywhere we //would a regular variable. 4

  5. Syntax: Setting Elements (cont) • Each element corresponds to one address in memory. • In C we must be careful with arrays a[0] because C does not stop us from a[1] attempting to access an element a[2] outside the array, eg. a[3] a[4] int a[5]; // Create an array of 5 integers. a[15] = 9; //But ‘a’ has only 5 elements //may crash program or cause //strange bugs. Array Syntax: Initializing • As with variables we can initialize an array at the moment we create it or afterwards. int a = 15; //Creates a variable and sets its value. //Create and initialize an array in one step. int a[] = { 8, 7, 15, 9} //Note compiler can determine //array size. //Create, and then initialize the elements. int a[4]; //In this case you must provide # elements. a[0] = 8; a[1] = 7; a[2] = 15; a[3] = 9; 5

  6. Character Arrays • In C strings are stored as arrays of characters. • The last character in the string should be the special string termination character '\0' (corresponds to 0). • You can pass your character arrays to C functions like printf char my_string[] = { 'h', 'e', 'l', 'l', 'o', '\0'}; //You can still access elements putchar( my_string[1] ); //outputs 'e' //Or pass to C functions. printf(“%s there!”, my_string); //prints “hello there.” Character Arrays • Note, the null terminator is ESSENTIAL for a string. Omitting it will likely cause any calls to printf() etc. to crash. • If you want to scan a ‘string’ you can use the null terminator as a marker for the end of the string. char my_string[] = { 'h', 'e', 'l', 'l', 'o', '\0'}; //count the length of my_string int pos = 0; while( my_string[pos] != '\0' ) { pos = pos + 1; } printf( "String: %s : is %d chars long\n", my_string, pos); 6

  7. Functions and Arrays • You can pass arrays to a function like any other variable (or as a pointer). • For 1d arrays adding the size is optional. #define N 10 int numbers[N]; void func1( int array[N]); //OK void func2( int array[] ); //Also OK void func3( int *array); //Also OK //When you invoke the function you don't use [ ] func1(numbers ); //correct func1(numbers[] ); //wrong - syntax error. Accessing Array Elements • Quite often you want to step through each element an array - use a for or while loop. • Use for most of the time, you must know the array length. //Count how many elements of array are greater than 100 int array[N]; array[0] = 237; //etc. int i; int count = 0; for( i = 0; i < N; i++) { if( array[i] > 100 ) count = count + 1; } 7

  8. Accessing Elements #define N 5 #define N 5 int array[N]; array[0] = 237; //etc. int array[N]; Code is array[0] = 237; //etc. equivalent. int i; int count= 0; int i; int c= 0; if( array[0] > 100) count = count +1; if( array[1] > 100) count = count +1; for( i = 0; i < N; i++) { if( array[2] > 100) count = count +1; if( (array[i] > 100 ) c = c + 1; if( array[3] > 100) count = count +1; } if( array[4] > 100) count = count +1; Using While Loops • In practice for loops are used more often. • Should only be used if the array has a terminating symbol/flag (like '\0' in strings). – This may be done with non-character arrays by specifying a special invalid element value. For example if the array recorded the weights of people you could use a negative value. 8

  9. While Loops #define END_OF_ARRAY -1.0 //Note that the terminator need not be in the final position. char astring[ ] = { 'h', 'e', 'l', 'l', 'o', '\0', 't', 'h', 'e', 'r', 'e', '\0' }; int i = 0; while( astring[i] != '\0' ) { // prints "hello" putchar( astring[i] ); i++; } double weights[ ] = { 123.0, 203.1, 176.0, 141.0, END_OF_ARRAY } i = 0; while( weights[i] != END_OF_ARRAY ) { //do something. //Note you must increment i or the loop runs forever! } Higher Dimensional Arrays • An array can have more than 1 dimension, they can have 2, 3, or more. • Syntax for creating is similar to 1-dimensional arrays. // A 1-d array int a[10]; //A 2-d array - perhaps used to store a chess/checker board. int b[8][8]; //A 3-d array int c[3][4][5]; //Higher - you could do this if you wanted to ... why? int e[2][3][4][5][6]; 9

  10. 2d-Arrays • Easiest to think about the array as storing elements in rows and columns. • First index is the row, second is the column. // create an array with two matrix[0][0] matrix[0][1] matrix[0][2] // rows and three columns int matrix[2][3]; matrix[1][0] matrix[1][1] matrix[1][2] // To set row 0 column 1 to 7 matrix[0][1] = 7; Functions • For 2d arrays the size of the 2nd dimension must be supplied when declaring a function (compiler only checks the second dimension). func1( int array[2][3] ); //OK func2( int array[ ][3] ); // Also OK func3( int array[ ][ ] ); //Not allowed. int a[2][3]; int b[3][3]; //Passing to functions is the same as for 1d arrays func1( a ); //OK same size. func1( b); //Will compile since b has 3 columns, but will likely //cause problems at run time. func2( a ); //OK same size. func2( b ); //OK because b has 3 columns. 10

  11. Accessing Elements in 2d Arrays • You can use 'nested' for loops. For example the following code sets every element in array2d to 0: #define ROWS 2 #define COLUMNS 2 int array2d[ROWS][COLUMNS]; int rw, cl; for( rw = 0; rw < ROWS; rw++ ) { for( cl = 0; cl < COLUMNS; cl++ ) { array2d[rw][cl] = 0; } } 3d-Arrays • A little trickier to think about, think of levels, rows, and columns. • First index is the level, second is the row, third is the column (not all elements shown in diagram) Array cube [2][0][1] [2][0][2] [2][0][0] // array with 3 levels, rows [1][0][0] [1][0][1] [1][0][2] // and columns [2][1][2] int cube[3][3][3]; [0][0][0] [0][0][1] [0][0][2] [1][1][2] // Set centre cell to 5 [0][1][0] [0][1][1] [0][1][2] cube[1][1][1] = 5; [2][2][2] [0][2][0] [0][2][1] [0][2][2] [1][2][2] 11

  12. Functions • For 3d arrays the size of the 2nd and 3rd dimensions must be supplied when declaring a function (only checks these). func1( int array[2][3][4] ); //OK func2( int array[ ][3][5] ); // Also OK func3( int array[ ][ ][4] ); //Not allowed. int a[2][3][4]; int b[3][3][5]; //Passing to functions is the same as for 1d arrays func1( a ); //OK same size. func2( b); //OK columns and rows are same. func2( a ); //Syntax error a has 3 rows, 4 columns. Accessing Elements in 3d Arrays • Use 'nested' for loops again, gets a bit messy. #define LEVELS 2 #define ROWS 2 #define COLUMNS 2 int array3d[LEVELS][ROWS][COLUMNS]; int lv, rw, cl; for( lv = 0; lv < LEVELS; lv++) { for( rw = 0; rw < ROWS; rw++ ) { for( cl = 0; cl < COLUMNS; cl++ ) { array2d[lv][rw][cl] = 0; } } } 12

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend