Department of Computer and Information Science, School of Science, IUPUI CSCI 230 Arrays Dale Roberts, Lecturer IUPUI droberts@cs.iupui.edu Dale Roberts Arrays Array Group of consecutive memory locations Same name and type, ex: an array of integers Name of array (Note that all elements of this array have the same name, my_array) To refer to an element, specify Array name Position number of particular element in the array Format: array_name[ position number ] First element at position 0 n element array named c: c[ 0 ], c[ 1 ]...c[ n – 1 ] Example: int my_array[12] my_array[0]= -45 value stored My_array[0] -45 My_array[1] 6 My_array[2] 0 My_array[3] 72 My_array[4] 1543 My_array[5] -89 My_array[6] 0 My_array[7] 62 My_array[8] -3 My_array[9] 1 Position number must be an integer number or an My_array[10] integer expression Example: my_array[1.5] ERROR!! my_array[i+j] valid if i and j are integers My_array[11] 6453 78 Position number of the element within array my_array Dale Roberts Arrays (cont.) Array elements are like normal variables my_array[8] = -3; printf( "%d", my_array[8]); Perform operations in subscript. If x equals 3: my_array[ 5 - 2 ] == my_array[ 3 ] == my_array[ x ] Declaring Arrays When declaring arrays, specify Name Type of array Number of elements: arrayType arrayName[ numberOfElements ]; Examples: int c[ 100 ]; /* reserve memory sufficient enough to store 100 elements of type integer */ float myArray[ 3284 ]; Dale Roberts Arrays (cont.) Declaring multiple arrays of same type: format similar to regular variables Example: int b[ 100 ], x[ 27 ]; Arrays may be declared to contain other data types Example: int a[ 100 ]; float b[ 100 ]; char c[ 100 ]; /* Strings are stored by using character arrays */ Example: #include <stdio.h> /* a simple program that uses arrays */ main( { int i, array_int[100]; for (i=0; i<100; i++) array_int[i]=0; for (i=0; i<100; i++) printf(“element %d: %d\n”, i, array_int[i]); } Dale Roberts Arrays (cont.) Initializers int n[5] = {1, 2, 3, 4, 5}; Example: main() { int i, a[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (i=0; i<10; i++) printf(“Element: %d\n”, a[i]); } If there are fewer initializations than elements in the array, then the remaining elements are automatically initialized to 0. int n[5] = {0} /* All elements 0 */ int a[10] = {1, 2} /* a[2] to a[9] are initialized to zeros */ int b[5] = {1, 2, 3, 4, 5, 6} /* syntax error */ C arrays have no bounds checking If size omitted, initializers determine it int n[ ] = { 1, 2, 3, 4, 5 }; /* 5 initializers, therefore 5 element array */ Scalable Arrays: a better programming style #define SIZE 10 int c[SIZE]; /* defines a symbolic constant size with value 10 */ Dale Roberts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /* Fig. 6.8: fig06_08.c Histogram printing program */ #include <stdio.h> #define SIZE 10 int main() { int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; int i, j; 1. Initialize array printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); for ( i = 0; i <= SIZE - 1; i++ ) { printf( "%7d%13d ", i, n[ i ]) ; for ( j = 1; j <= n[ i ]; j++ ) printf( "%c", '*' ); printf( "\n" ); } return 0; } 2. Loop /* print one bar */ 3. Print Program output Element 0 1 2 3 4 5 6 7 8 9 Value 19 3 15 7 11 9 13 5 17 1 Histogram ******************* *** *************** ******* *********** ********* ************* ***** ***************** * Dale Roberts Arrays (cont.) Example: #include <stdio.h> #define SIZE 100 main() { int i, a[SIZE]; int sum = 0; … for (i=0; i< size; i++) sum = sum + a[i]; printf(“sum: %d\n, sum); } Dale Roberts Character Arrays Character arrays String is really a static array of characters, ex: “first” Character arrays can be initialized using string literals char string1[] = "first"; Null character '\0' terminates strings f i r s t \0 string1 actually has 6 elements Null character (indicates string termination) It is equivalent to char string1[] = { 'f', 'i', 'r', 's', 't', '\0' }; Can access individual characters string1[ 3 ] is character ‘s’ Array name is address of array, so & not needed for scanf char string2[20]; & is NOT used, why? scanf( "%s", string2 ); /* can read a string with max of size 19 and a null character */ Reads characters until whitespace (space, tab, carriage-return, newline, vertical tab) encountered Can write beyond end of array, be careful Dale Roberts Passing Arrays to Functions Passing arrays To pass an array argument to a function, specify the name of the array without any brackets int myArray[ 24 ]; ... myFunction( myArray, 24 ); ... Pass array name Size is also often sent as an argument Array size usually passed to function Arrays passed call-by-reference the called functions can modify the element values in the caller’s original array Name of array is the address of first element of the array Function knows where the array is stored. Therefore, when the called function modifies array elements in its function body, it is modifying the actual elements of array in the original memory locations main() myFunction() … myArray Dale Roberts Passing Arrays to Functions (cont.) Example: output: #include <stdio.h> main() { int a[10]; printf(“a = %p \n &a[0] = %p\n”, a, &a[0]); } a = FFEE &a[0] = FFEE Passing array elements Individual elements of an array are passed by call-by-value Pass subscripted name (i.e., myArray[ 3 ]) to function Example: compare(a[0], a[1]); will be passed by value An array is a vector while individual elements are scalars. Function prototype void modifyArray( int b[], int arraySize ); Parameter names optional in prototype int b[] could be written int [] int arraySize could be simply int Dale Roberts 1 2 */ 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ); 29 30 31 32 /* Fig. 6.13: fig06_13.c Passing arrays and individual array elements to functions #include <stdio.h> #define SIZE 5 void modifyArray( int [], int ); void modifyElement( int ); /* appears strange */ int main() { int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; Function definitions printf( "Effects of passing entire array call " "by reference:\n\nThe values of the " "original array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) printf( "%3d", a[ i ] ); Entire arrays passed call-byreference, and can be modified printf( "\n" ); modifyArray( a, SIZE ); /* passed call by reference */ printf( "The values of the modified array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) Array elements passed call-byprintf( "%3d", a[ i ] ); value, and cannot be modified printf( "\n\n\nEffects of passing array element call " "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] modifyElement( a[ 3 ] ); printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); return 0; Pass array to a function Pass array element to a function } Print Dale Roberts 33 34 void modifyArray( int b[], int size ) 35 { 36 Function definitions int j; 37 38 39 for ( j = 0; j <= size - 1; j++ ) b[ j ] *= 2; 40 } 41 42 void modifyElement( int e ) 43 { 44 printf( "Value in modifyElement is %d\n", e *= 2 ); 45 } Program Output Effects of passing entire array call by reference: The values of 0 1 2 3 The values of 0 2 4 6 the original array are: 4 the modified array are: 8 Effects of passing array element call by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[3] is 6 Dale Roberts Multiple-Dimensional Arrays Multiple subscripted arrays Arrays require at least two subscripts to identify a particular element ANSI C standard allows at least 12 array subscripts A: scalar 2D Arrays A[0]: 1D array 1-Dimensional vector A[0][0]: (2 subscripts) 2D array (matrix) 2-dimensional vector Tables with rows and columns (m by n array) Like matrices: specify row, then column Column 0 Column 1 Column 2 Column 3 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 ] Column subscript Array name Row subscript A common error is to use math matrix notation a(1,2) Dale Roberts Multiple-Subscripted Arrays Initialization 1 2 int b[2][2] = {{ 1, 2 }, { 3, 4 } }; 3 int c[3][2] = {{ 1, 2 }, { 3, 4 }, { 5, 6 }}; 1 2 3 4 5 6 1 2 3 4 5 6 4 Actual storage in the memory rows by rows -“row-major” Initializers grouped by row in braces If not enough, unspecified elements set to zero int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Referencing elements 1 0 Specify row, then column 3 4 printf( "%d", b[ 0 ][ 1 ] ); Dale Roberts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /* Fig. 6.22: fig06_22.c Double-subscripted array example */ #include <stdio.h> #define STUDENTS 3 #define EXAMS 4 const forces pass-by-value even though the parameter is a pointer int minimum( const int [][ EXAMS ], int, int ); int maximum( const int [][ EXAMS ], int, int ); double average( const int [], int ); void printArray( const int [][ EXAMS ], int, int ); Initialize variables Define functions to take double scripted arrays Each row is a particular student, each column is the int main() grades on the exam. Proper naming of the #defined { constants is important to convey meaning. int student; const int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, Initialize studentgrades[][] { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; printf( "The array is:\n" ); printArray( studentGrades, STUDENTS, EXAMS ); printf( "\n\nLowest grade: %d\nHighest grade: %d\n", minimum( studentGrades, STUDENTS, EXAMS ), maximum( studentGrades, STUDENTS, EXAMS ) ); Call functions minimum, maximum, and average for ( student = 0; student <= STUDENTS - 1; student++ ) printf( "The average grade for student %d is %.2f\n", student, average( studentGrades[ student ], EXAMS ) ); return 0; } Dale Roberts 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 /* Find the minimum grade */ int minimum( const int grades[][ EXAMS ], int pupils, int tests ) { int i, j, lowGrade = 100; for ( i = 0; i <= pupils - 1; i++ ) for ( j = 0; j <= tests - 1; j++ ) if ( grades[ i ][ j ] < lowGrade ) lowGrade = grades[ i ][ j ]; Why is it important to initialize lowGrade to the highest possible grade, and highGrade to the lowest possible grade? return lowGrade; } /* Find the maximum grade */ int maximum( const int grades[][ EXAMS ], int pupils, int tests ) { int i, j, highGrade = 0; for ( i = 0; i <= pupils - 1; i++ ) for ( j = 0; j <= tests - 1; j++ ) if ( grades[ i ][ j ] > highGrade ) highGrade = grades[ i ][ j ]; return highGrade; } /* Determine the average grade for a particular exam */ double average( const int setOfGrades[], int tests ) { Dale Roberts 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 int i, total = 0; for ( i = 0; i <= tests - 1; i++ ) total += setOfGrades[ i ]; return ( double ) total / tests; } /* Print the array */ void printArray( const int grades[][ EXAMS ], int pupils, int tests ) { int i, j; printf( " [0] [1] [2] Define function [3]" ); for ( i = 0; i <= pupils - 1; i++ ) { printf( "\nstudentGrades[%d] ", i ); for ( j = 0; j <= tests - 1; j++ ) printf( "%-5d", grades[ i ][ j ] ); } } Program Output The array is: [0] studentGrades[0] 77 studentGrades[1] 96 studentGrades[2] 70 [1] 68 87 90 [2] 86 89 86 [3] 73 78 81 Lowest grade: 68 Highest grade: 96 The average grade for student 0 is 76.00 The average grade for student 1 is 87.50 The average grade for student 2 is 81.75 Dale Roberts Sorting Arrays Sorting data Important computing application Virtually every organization must sort some data Bubble sort (sinking sort) Several passes through the array Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged Repeat Example: original: 3 4 2 6 7 pass 1: 3 2 4 6 7 pass 2: 2 3 4 6 7 Small elements "bubble" to the top Dale Roberts Case Study: Computing Mean, Median and Mode Using Arrays Mean – average Median – number in middle of sorted list Example: 1, 2, 3, 4, 5 3 is the median Mode – number that occurs most often Example: 1, 1, 1, 2, 3, 3, 4, 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 is the mode /* Fig. 6.16: fig06_16.c This program introduces the topic of survey data analysis. It computes the mean, median, and mode of the data */ #include <stdio.h> #define SIZE 99 void void void void void mean( const int [] ); median( int [] ); mode( int [], const int [] ) ; bubbleSort( int [] ); printArray( const int [] ); Function prototypes int main() { int frequency[ 10 ] = { 0 }; Dale Roberts 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 int response[ { 6, 7, 8, 7, 8, 9, 6, 7, 8, 7, 8, 9, 6, 7, 8, 7, 8, 9, 5, 6, 7, 7, 8, 9, 7, 4, 4, 4, 5, 6, SIZE ] = 9, 8, 7, 5, 9, 8, 9, 3, 9, 8, 9, 8, 7, 8, 7, 8, 9, 8, 2, 5, 3, 6, 8, 7, 2, 5, 3, 1, 6, 5, 8, 7, 8, 9, 9, 9, 9, 8, 8, 7, 9, 8, 7, 7, 8, 7, 4, 9, 7, 8, 8, 9, 7, 8, 8, 7, 8, 9, 9, 2, 5, 3, 6, 4, 7, 8, 5, 6, 7 }; mean( response ); median( response ); mode( frequency, response ); return 0; } void mean( const int answer[] ) { int j, total = 0; printf( "%s\n%s\n%s\n", "********", " Initialize array Call functions mean, median, and mode Define function mean Mean", "********" ); for ( j = 0; j <= SIZE - 1; j++ ) total += answer[ j ]; printf( "The mean is the average value of the data\n" "items. The mean is equal to the total of\n" "all the data items divided by the number\n" "of data items ( %d ). The mean value for\n" "this run is: %d / %d = %.4f\n\n", SIZE, total, SIZE, ( double ) total / SIZE ); } Dale Roberts 50 51 void median( int answer[] ) 52 { 53 54 55 printf( "\n%s\n%s\n%s\n%s", Define function median "********", " Median", "********", "The unsorted array of responses is" ); 56 57 printArray( answer ); 58 59 bubbleSort( answer ); printf( "\n\nThe sorted array is" ); 60 61 printArray( answer ); printf( "\n\nThe median is element %d of\n" 62 63 "the sorted %d element array.\n" "For this run the median is %d\n\n", 64 SIZE / 2, SIZE, answer[ SIZE / 2 ] ); 65 } 66 67 void mode( int freq[], const int answer[] ) 68 { 69 int rating, j, h, largest = 0, modeValue = 0; 70 71 printf( "\n%s\n%s\n%s\n", 72 "********", " Mode", "********" ); 73 74 for ( rating = 1; rating <= 9; rating++ ) 75 freq[ rating ] = 0; 76 77 for ( j = 0; j <= SIZE - 1; j++ ) 78 ++freq[ answer[ j ] ]; 79 Sort Array Print middle element Is this computation of the median element correct? Notice that SIZE must be add for this to be correct. Is SIZE odd? Define function mode Notice how the subscript in freq[] is the value of an element in response[] (answer[]) Increase frequency[] depending on response[] Dale Roberts 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 } 102 printf( "%s%11s%19s\n\n%54s\n%54s\n\n", "Response", "Frequency", "Histogram", "1 1 2 2", "5 0 5 0 5" ); for ( rating = 1; rating <= 9; rating++ ) { printf( "%8d%11d ", rating, freq[ rating ] ); if ( freq[ rating ] > largest ) { largest = freq[ rating ]; modeValue = rating; } for ( h = 1; h <= freq[ rating ]; h++ ) printf( "*" ); printf( "\n" ); } Print stars depending on value of frequency[] printf( "The mode is the most frequent value.\n" "For this run the mode is %d which occurred" " %d times.\n", modeValue, largest ); Dale Roberts 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 void bubbleSort( int a[] ) { int pass, j, hold; for ( pass = 1; pass <= SIZE - 1; pass++ ) for ( j = 0; j <= SIZE - 2; j++ ) if ( a[ hold a[ j a[ j } j = ] + Define bubbleSort Bubble sort can make the smallest values “sink” by scanning top to bottom using < or make the largest values “float” by scanning bottom to top using >. ] > a[ j + 1 ] ) { a[ j ]; Bubble sort: if elements = a[ j + 1 ]; out of order, swap them. 1 ] = hold; } void printArray( const int a[] ) { int j; for ( j = 0; j <= SIZE - 1; j++ ) { if ( j % 20 == 0 ) printf( "\n" ); 127 128 Define printArray printf( "%2d", a[ j ] ); } 129 } Dale Roberts Program Output ******** Mean ******** The mean is the average value of the data items. The mean is equal to the total of all the data items divided by the number of data items (99). The mean value for this run is: 681 / 99 = 6.8788 ******** Median ******** The unsorted array of responses is 7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 8 6 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 9 6 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 3 5 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 8 7 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7 The sorted 1 2 2 2 3 5 6 6 6 6 7 7 7 7 7 8 8 8 8 8 9 9 9 9 9 array 3 3 3 6 6 6 7 7 7 8 8 8 9 9 9 is 4 4 6 6 7 7 8 8 9 9 4 7 7 8 9 4 7 7 8 9 4 7 7 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 9 5 7 8 8 The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** Response Frequency Histogram 5 1 0 1 5 2 0 2 5 1 1 * 2 3 *** 3 4 **** 4 5 ***** 5 8 ******** 6 9 ********* 7 23 *********************** 8 27 *************************** 9 19 ******************* The mode is the most frequent value. For this run the mode is 8 which occurred 27 times. Dale Roberts Searching Arrays: Linear Search vs Binary Search Search an array for a key value Linear search Simple Compare each element of array with key value Useful for small and unsorted arrays Binary search For sorted arrays Compares middle element with key If equal, match found If key < middle, looks in first half of array If key > middle, looks in last half Repeat Very fast; at most n steps, where 2n > number of elements 30 element array takes at most 5 steps 25 > 30 so at most 5 steps Dale Roberts