CHTP5e 06 C Arrays
CHTP5e 06 C Arrays
6
C Arrays
Begin at the beginning, and go on till you come to the end: then stop.
Lewis Carroll
OBJECTIVES
In this chapter you will learn: To use the array data structure to represent lists and tables of values. To define an array, initialize an array and refer to individual elements of an array. To define symbolic constants. To pass arrays to functions. To use arrays to store, sort and search lists and tables of values. To define and manipulate multiple-subscripted arrays.
2007 Pearson Education, Inc. All rights reserved.
6.1 6.2
Introduction Arrays
6.3
6.4 6.5
Defining Arrays
Array Examples Passing Arrays to Functions
6.6
6.7 6.8
Sorting Arrays
Case Study: Computing Mean, Median and Mode Using Arrays Searching Arrays
6.9
Multiple-Subscripted Arrays
6.1 Introduction
Arrays
Structures of related data items
Static entity same size throughout program Dynamic data structures discussed in Chapter 12
6.2 Arrays
Array
Group of consecutive memory locations Same name and type
Format:
arrayname[ position number ] First element at position 0 n element array named c:
- c[ 0 ], c[ 1 ]...c[ n 1 ]
6.2 Arrays
Array elements are like normal variables
c[ 0 ] = 3; printf( "%d", c[ 0 ] );
10
Operators
[] ++ * + < == && || ?: = , += -= *= /= %= () -/ <= != > >= ! % (type)
Associativity
left to right right to left left to right left to right left to right left to right left to right left to right right to left right to left left to right
Type
highest unary multiplicative additive relational equality logical AND logical OR conditional assignment comma
11
Examples:
int c[ 10 ]; float myArray[ 3284 ];
12
- All elements 0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Fig. 6.3: fig06_03.c initializing an array */ #include <stdio.h> /* function main begins program execution */ int main( void ) { int n[ 10 ]; /* n is an array of 10 integers */ int i; /* counter */ /* initialize elements of array n to 0 */ for ( i = 0; i < 10; i++ ) { n[ i ] = 0; /* set element at location i to 0 */ } /* end for */ printf( "%s%13s\n", "Element", "Value" ); /* output contents of array n in tabular format */ for ( i = 0; i < 10; i++ ) { printf( "%7d%13d\n", i, n[ i ] ); } /* end for */ return 0; /* indicates successful termination */
13
Outline
fig06_03.c
25 } /* end main */
Element 0 1 2 3 4 5 6 7 8 9
Value 0 0 0 0 0 0 0 0 0 0
14
Outline
fig06_03.c
(2 of 2 )
1 2 3 4 5 6
/* Fig. 6.4: fig06_04.c Initializing an array with an initializer list */ #include <stdio.h> /* function main begins program execution */ int main( void ) /* use initializer list to initialize array n */ int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; int i; /* counter */ printf( "%s%13s\n", "Element", "Value" ); /* output contents of array in tabular format */ for ( i = 0; i < 10; i++ ) { printf( "%7d%13d\n", i, n[ i ] ); } /* end for */
15
Outline
7 { 8 9 10 11 12 13 14 15 16 17 18
fig06_04.c
(1 of 2 )
Element 0 1 2 3 4 5 6 7 8 9
Value 32 27 64 18 95 14 90 70 60 37
16
Outline
fig06_04.c
(2 of 2 )
17
18
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* Fig. 6.5: fig06_05.c Initialize the elements of array s to the even integers from 2 to 20 */ #include <stdio.h> #define directive tells compiler #define SIZE 10 /* maximum size of array */ /* function main begins program execution */ int main( void ) { /* symbolic constant SIZE can be used to specify array size */ int s[ SIZE ]; /* array s has SIZE elements */ int j; /* counter */ for ( j = 0; j < SIZE; j++ ) { /* set the values */ s[ j ] = 2 + 2 * j; } /* end for */ printf( "%s%13s\n", "Element", "Value" ); /* output contents of array s in tabular format */ for ( j = 0; j < SIZE; j++ ) { printf( "%7d%13d\n", j, s[ j ] ); } /* end for */ return 0; /* indicates successful termination */
19
Outline
(1 of 2 )
SIZE is replaced with 10 by the compiler, so array s has 10 elements for loop initializes each array element separately
25 26 } /* end main */
Element 0 1 2 3 4 5 6 7 8 9
Value 2 4 6 8 10 12 14 16 18 20
20
Outline
fig06_05.c
(2 of 2 )
21
22
23
24
25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* Fig. 6.6: fig06_06.c Compute the sum of the elements of the array */ #include <stdio.h> #define SIZE 12 /* function main begins program execution */ int main( void ) { /* use initializer list to initialize array */ int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 }; int i; /* counter */ int total = 0; /* sum of array */ /* sum contents of array a */ for ( i = 0; i < SIZE; i++ ) { total += a[ i ]; } /* end for */
26
Outline
fig06_06.c
initializer list initializes all array elements simultaneously for loop adds each element of the array to variable total
19 printf( "Total of array element values is %d\n", total ); 20 21 return 0; /* indicates successful termination */ 22 23 } /* end main */ Total of array element values is 383
1 2 3 4 5 6 7 8
/* Fig. 6.7: fig06_07.c Student poll program */ #include <stdio.h> #define RESPONSE_SIZE 40 /* define array sizes */ #define FREQUENCY_SIZE 11 /* function main begins program execution */ int main( void ) int answer; /* counter to loop through 40 responses */ int rating; /* counter to loop through frequencies 1-10 */ /* initialize frequency counters to 0 */ int frequency[ FREQUENCY_SIZE ] = { 0 }; /* place the survey responses in the responses array */ int responses[ RESPONSE_SIZE ] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; /* for each answer, select value of an element of array responses and use that value as subscript in array frequency to determine element to increment */ for ( answer = 0; answer < RESPONSE_SIZE; answer++ ) { ++frequency[ responses [ answer ] ]; } /* end for */
27
Outline
#define directives create symbolic constants
fig06_07.c
9 { 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
(1 of 2 )
frequency array is defined with 11 elements responses array is defined with 40 elements and its elements are initialized
28 29 30 31 32 33
/* display results */ printf( "%s%17s\n", "Rating", "Frequency" ); /* output the frequencies in a tabular format */ for ( rating = 1; rating < FREQUENCY_SIZE; rating++ ) { printf( "%6d%17d\n", rating, frequency[ rating ] );
28
Outline
34 } /* end for */ 35 36 return 0; /* indicates successful termination */ 37 38 } /* end main */ Rating 1 2 3 4 5 6 7 8 9 10 Frequency 2 2 2 2 5 11 5 7 1 3
fig06_07.c
(2 of 2 )
29
30
31
32
33
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
/* Fig. 6.8: fig06_08.c Histogram printing program */ #include <stdio.h> #define SIZE 10 /* function main begins program execution */ int main( void ) { /* use initializer list to initialize array n */ int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; int i; /* outer for counter for array elements */ int j; /* inner for counter counts *s in each histogram bar */ printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); /* for each element of array n, output a bar of the histogram */ for ( i = 0; i < SIZE; i++ ) { printf( "%7d%13d ", i, n[ i ]) ;
34
Outline
fig06_08.c
(1 of 2 )
for ( j = 1; j <= n[ i ]; j++ ) { /* print one bar */ printf( "%c", '*' ); } /* end inner for */ printf( "\n" ); /* end a histogram bar */ } /* end outer for */ return 0; /* indicates successful termination */
29 } /* end main */
Element 0 1 2 3 4 5 6 7 8 9
Value 19 3 15 7 11 9 13 5 17 1
Histogram ******************* *** *************** ******* *********** ********* ************* ***** ***************** *
35
Outline
fig06_08.c
(2 of 2 )
1 2 3 4 5 6 7 8
/* Fig. 6.9: fig06_09.c Roll a six-sided die 6000 times */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 7 /* function main begins program execution */
36
Outline
fig06_09.c
9 int main( void ) 10 { 11 int face; /* random die value 1 - 6 */ 12 13 14 15 16 17 18 19 20 21 /* roll die 6000 times */ for ( roll = 1; roll <= 6000; roll++ ) { face = 1 + rand() % 6; ++frequency[ face ]; /* replaces 26-line switch of Fig. 5.8 */ } /* end for */ int roll; /* roll counter 1-6000 */ int frequency[ SIZE ] = { 0 }; /* clear counts */ srand( time( NULL ) ); /* seed random-number generator */
(1 of 2 )
for loop uses one array to track number of times each number is rolled instead of using 6 variables and a switch statement
22 23 24 25 26 27 28 29 printf( "%s%17s\n", "Face", "Frequency" ); /* output frequency elements 1-6 in tabular format */ for ( face = 1; face < SIZE; face++ ) { printf( "%4d%17d\n", face, frequency[ face ] ); } /* end for */
37
Outline
fig06_09.c
30 return 0; /* indicates successful termination */ 31 32 } /* end main */ Face 1 2 3 4 5 6 Frequency 1029 951 987 1033 1010 990
(2 of 2 )
38
- Null character '\0' terminates strings - string1 actually has 6 elements It is equivalent to
char string1[] = { 'f', 'i', 'r', 's', 't', '\0' };
- Reads characters until whitespace encountered - Be careful not to write past end of array, as it is possible to do so
39
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
/* Fig. 6.10: fig06_10.c Treating character arrays as strings */ #include <stdio.h> /* function main begins program execution */ int main( void ) { char string1[ 20 ]; /* reserves 20 characters */ char string2[] = "string literal"; /* reserves 15 characters */ int i; /* counter */ /* read string from user into array string1 */ printf("Enter a string: ");
40
Outline
fig06_10.c
(1 of 2 )
string2 array is defined with one element for each character, so 15 elements including null character /0
scanf( "%s", string1 ); /* input ended by whitespace character */ /* output strings */ printf( "string1 is: %s\nstring2 is: %s\n" "string1 with spaces between characters is:\n", string1, string2 ); /* output characters until null character is reached */ for ( i = 0; string1[ i ] != '\0'; i++ ) { printf( "%c ", string1[ i ] ); } /* end for */ printf( "\n" ); return 0; /* indicates successful termination */
30 } /* end main */
string: Hello there is: Hello is: string literal with spaces between characters is: o
41
Outline
fig06_10.c
(2 of 2 )
42
1 2 3 4 5 6 7 8 9
/* Fig. 6.11: fig06_11.c Static arrays are initialized to zero */ #include <stdio.h> void staticArrayInit( void ); /* function prototype */ void automaticArrayInit( void ); /* function prototype */ /* function main begins program execution */ int main( void ) printf( "First call to each function:\n" ); staticArrayInit(); automaticArrayInit(); printf( "\n\nSecond call to each function:\n" ); staticArrayInit(); automaticArrayInit();
43
Outline
fig06_11.c
(1 of 4 )
10 { 11 12 13 14 15 16 17 18
23 /* function to demonstrate a static local array */ 24 void staticArrayInit( void ) 25 { 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 /* output contents of array1 */ for ( i = 0; i <= 2; i++ ) { printf( "array1[ %d ] = %d ", i, array1[ i ] ); } /* end for */ printf( "\nValues on exiting staticArrayInit:\n" ); /* modify and output contents of array1 */ for ( i = 0; i <= 2; i++ ) { /* initializes elements to 0 first time function is called */ static int array1[ 3 ]; int i; /* counter */
44
Outline
static array is created only once, when staticArrayInit is first called
fig06_11.c
(2 of 4 )
45 46 /* function to demonstrate an automatic local array */ 47 void automaticArrayInit( void ) 48 { 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 /* initializes elements each time function is called */ int array2[ 3 ] = { 1, 2, 3 }; int i; /* counter */
45
Outline
fig06_11.c
printf( "\n\nValues on entering automaticArrayInit:\n" ); /* output contents of array2 */ for ( i = 0; i <= 2; i++ ) { printf("array2[ %d ] = %d } /* end for */ ", i, array2[ i ] );
(3 of 4 )
printf( "\nValues on exiting automaticArrayInit:\n" ); /* modify and output contents of array2 */ for ( i = 0; i <= 2; i++ ) { printf( "array2[ %d ] = %d ", i, array2[ i ] += 5 ); } /* end for */
First call to each function: Values on array1[ 0 Values on array1[ 0 Values on array2[ 0 Values on array2[ 0 entering staticArrayInit: ] = 0 array1[ 1 ] = 0 array1[ 2 ] = 0 exiting staticArrayInit: ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5 entering automaticArrayInit: ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3 exiting automaticArrayInit: ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8
46
Outline
fig06_11.c
(4 of 4 )
Second call to each function: Values on array1[ 0 Values on array1[ 0 Values on array2[ 0 Values on array2[ 0 entering staticArrayInit: ] = 5 array1[ 1 ] = 5 array1[ 2 ] = 5 exiting staticArrayInit: ] = 10 array1[ 1 ] = 10 array1[ 2 ] = 10 entering automaticArrayInit: ] = 1 array2[ 1 ] = 2 array2[ 2 ] = 3 exiting automaticArrayInit: ] = 6 array2[ 1 ] = 7 array2[ 2 ] = 8
47
48
Arrays passed call-by-reference Name of array is address of first element Function knows where the array is stored
- Modifies original memory locations
49
50
1 2 3 4 5 6 7 8 9 10 11
/* Fig. 6.12: fig06_12.c The name of an array is the same as &array[ 0 ] */ #include <stdio.h> /* function main begins program execution */ int main( void ) { char array[ 5 ]; /* define an array of size 5 */ printf( " array = %p\n&array[0] = %p\n array, &array[ 0 ], &array ); &array = %p\n",
51
Outline
fig06_12.c
12 13 return 0; /* indicates successful termination */ 14 15 } /* end main */ array = 0012FF78 &array[0] = 0012FF78 &array = 0012FF78
52
1 2 3 4 5 6 7 8
/* Fig. 6.13: fig06_13.c Passing arrays and individual array elements to functions */ #include <stdio.h> #define SIZE 5 /* function prototypes */ void modifyArray( int b[], int size ); void modifyElement( int e );
53
Outline
9 10 /* function main begins program execution */ 11 int main( void ) 12 { 13 int a[ SIZE ] = { 0, 1, 2, 3, 4 }; /* initialize a */ 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 int i; /* counter */
fig06_13.c
printf( "Effects of passing entire array by reference:\n\nThe " "values of the original array are:\n" ); /* output original array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", a[ i ] ); } /* end for */ printf( "\n" ); /* pass array a to modifyArray by reference */ modifyArray( a, SIZE ); printf( "The values of the modified array are:\n" );
31 32 33 34 35 36 37 38 39 40 41 42 43
/* output modified array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", a[ i ] ); } /* end for */ /* output value of a[ 3 ] */ printf( "\n\n\nEffects of passing array element " "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */ /* output value of a[ 3 ] */ printf( "The value of a[ 3 ] is %d\n", a[ 3 ] );
54
Outline
fig06_13.c
(2 of 3 )
44 45 return 0; /* indicates successful termination */ 46 47 } /* end main */ 48 49 /* in function modifyArray, "b" points to the original array "a" 50 in memory */ 51 void modifyArray( int b[], int size ) 52 { 53 54 55 56 57 58 59 int j; /* counter */ /* multiply each array element by 2 */ for ( j = 0; j < size; j++ ) { b[ j ] *= 2; } /* end for */
61 62 /* in function modifyElement, "e" is a local copy of array element 63 a[ 3 ] passed from main */ 64 void modifyElement( int e ) 65 { 66 /* multiply parameter by 2 */
55
Outline
67 printf( "Value in modifyElement is %d\n", e *= 2 ); 68 } /* end function modifyElement */ Effects of passing entire array 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
fig06_13.c
(3 of 3 )
Effects of passing array element by value: The value of a[3] is 6 Value in modifyElement is 12 The value of a[ 3 ] is 6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Fig. 6.14: fig06_14.c Demonstrating the const type qualifier with arrays */ #include <stdio.h> void tryToModifyArray( const int b[] ); /* function prototype */ /* function main begins program execution */ int main( void ) { int a[] = { 10, 20, 30 }; /* initialize a */ tryToModifyArray( a ); printf("%d %d %d\n", a[ 0 ], a[ 1 ], a[ 2 ] ); return 0; /* indicates successful termination */
56
Outline
fig06_14.c
18 } /* end main */ 19 20 /* in function tryToModifyArray, array b is const, so it cannot be 21 used to modify the original array a in main. */ 22 void tryToModifyArray( const int b[] ) 23 { 24 b[ 0 ] /= 2; /* error */ 25 b[ 1 ] /= 2; /* error */ 26 b[ 2 ] /= 2; /* error */ 27 } /* end function tryToModifyArray */
Compiling... FIG06_14.C fig06_14.c(24) : error C2166: l-value specifies const object fig06_14.c(25) : error C2166: l-value specifies const object fig06_14.c(26) : error C2166: l-value specifies const object
57
Outline
fig06_14.c
(2 of 2 )
58
59
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
60
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
/* Fig. 6.15: fig06_15.c This program sorts an array's values into ascending order */ #include <stdio.h> #define SIZE 10 /* function main begins program execution */ int main( void ) { /* initialize a */ int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; int pass; /* passes counter */ int i; /* comparisons counter */ int hold; /* temporary location used to swap array elements */ printf( "Data items in original order\n" ); /* output original array */ for ( i = 0; i < SIZE; i++ ) { printf( "%4d", a[ i ] ); } /* end for */ /* bubble sort */ /* loop to control number of passes */ for ( pass = 1; pass < SIZE; pass++ ) { /* loop to control number of comparisons per pass */ for ( i = 0; i < SIZE - 1; i++ ) {
61
Outline
fig06_15.c
(1 of 2 )
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 }
/* compare adjacent elements and swap them if first element if ( a[ hold a[ i a[ i is greater than second element */ i ] > a[ i + 1 ] ) { = a[ i ]; If any two array elements are out of ] = a[ i + 1 ]; order, the function swaps them + 1 ] = hold;
62
Outline
} /* end if */ } /* end inner for */ } /* end outer for */ printf( "\nData items in ascending order\n" ); /* output sorted array */ for ( i = 0; i < SIZE; i++ ) { printf( "%4d", a[ i ] ); } /* end for */ printf( "\n" ); return 0; /* indicates successful termination */
fig06_15.c
(2 of 2 )
45 68
37 89
63
6.7 Case Study: Computing Mean, Median and Mode Using Arrays
Mean average
1 2 3 4 5 6 7 8 9 10 11 12
/* 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 /* function prototypes */ void mean( const int answer[] ); void median( int answer[] ); void mode( int freq[], const int answer[] ) ; void bubbleSort( int a[] ); void printArray( const int a[] );
64
Outline
fig06_16.c
(1 of 6 )
13 14 /* function main begins program execution */ 15 int main( void ) 16 { 17 int frequency[ 10 ] = { 0 }; /* initialize array frequency */ 18 19 20 21 22 23 24 25 26 27 28 29 30 /* initialize int response[ { 6, 7, 8, 7, 8, 9, 6, 7, 8, 7, 6, 7, 5, 7, 8, 7, 8, 6, 8, 9, 8, 9, 7, 9, array response SIZE ] = 9, 8, 7, 8, 9, 5, 9, 8, 7, 8, 9, 3, 9, 8, 7, 8, 7, 8, 2, 6, 9, 8, 9, 5, 8, 8, 7, 8, 3, 7, 9, 9, 9, 9, 8, 7, 8, 7, 4, 9, */ 8, 9, 7, 8, 8, 7, 8, 9, 5, 6, 7, 9, 2, 3, 4, 8,
7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 4, 5, 6, 1, 6, 5, 7, 8, 7 };
31 32
65
/* process responses */
33 mean( response ); 34 median( response ); 35 mode( frequency, response ); 36 37 return 0; /* indicates successful termination */ 38 39 } /* end main */ 40 41 /* calculate average of all response values */ 42 void mean( const int answer[] ) 43 { 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 int j; /* counter for totaling array elements */ int total = 0; /* variable to hold sum of array elements */ printf( "%s\n%s\n%s\n", "********", " /* total response values */ for ( j = 0; j < SIZE; j++ ) { total += answer[ j ]; } /* end for */ 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", double ) total / SIZE ); Mean", "********" );
Outline
fig06_16.c
(2 of 6 )
61 62 /* sort array and determine median element's value */ 63 void median( int answer[] ) 64 { 65 66 67 68 69 70 71 72 73 printf( "\n%s\n%s\n%s\n%s", "********", " Median", "********", "The unsorted array of responses is" ); printArray( answer ); /* output unsorted array */ bubbleSort( answer ); /* sort array */ printf( "\n\nThe sorted array is" );
66
Outline
fig06_16.c
(3 of 6 )
Once the array is sorted, the median will be the value of the middle element
74 printArray( answer ); /* output sorted array */ 75 76 /* display median element */ 77 printf( "\n\nThe median is element %d of\n" 78 "the sorted %d element array.\n" 79 "For this run the median is %d\n\n", 80 SIZE / 2, SIZE, answer[ SIZE / 2 ] ); 81 } /* end function median */ 82 83 /* determine most frequent response */ 84 void mode( int freq[], const int answer[] ) 85 { 86 int rating; /* counter for accessing elements 1-9 of array freq */ 87 int j; /* counter for summarizing elements 0-98 of array answer */ 88 int h; /* counter for diplaying histograms of elements in array freq */ 89 int largest = 0; /* represents largest frequency */ 90 int modeValue = 0; /* represents most frequent response */
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 /* initialize frequencies to 0 */ for ( rating = 1; rating <= 9; rating++ ) { freq[ rating ] = 0; } /* end for */ /* summarize frequencies */ for ( j = 0; j < SIZE; j++ ) { ++freq[ answer[ j ] ]; } /* end for */ /* output headers for result columns */ printf( "%s%11s%19s\n\n%54s\n%54s\n\n", "Response", "Frequency", "Histogram", "1 1 2 2", "5 0 5 0 5" ); printf( "\n%s\n%s\n%s\n", "********", " Mode", "********" );
67
Outline
fig06_16.c
(4 of 6 )
/* output results */ for ( rating = 1; rating <= 9; rating++ ) { printf( "%8d%11d ", rating, freq[ rating ] ); /* keep track of mode value and largest frequency value */ if ( freq[ rating ] > largest ) { largest = freq[ rating ]; modeValue = rating; } /* end if */
119 120 121 122 123 124 125 126 127 128 129 130 131 132
68
/* output histogram bar representing frequency value */ for ( h = 1; h <= freq[ rating ]; h++ ) { printf( "*" ); } /* end inner for */ printf( "\n" ); /* being new line of output */ } /* end outer for */ /* display the mode value */ printf( "The mode is the most frequent value.\n" "For this run the mode is %d which occurred" " %d times.\n", modeValue, largest ); } /* end function mode */
Outline
fig06_16.c
(5 of 6 )
133 134 /* function that sorts an array with bubble sort algorithm */ 135 void bubbleSort( int a[] ) 136 { 137 int pass; /* pass counter */ 138 int j; /* comparison counter */ 139 int hold; /* temporary location used to swap elements */ 140 141 142 143 144 145 146 /* loop to control number of passes */ for ( pass = 1; pass < SIZE; pass++ ) { /* loop to control number of comparisons per pass */ for ( j = 0; j < SIZE - 1; j++ ) {
/* swap elements if out of order */ if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } /* end if */ } /* end inner for */
69
Outline
fig06_16.c
155 156 } /* end outer for */ 157 158 } /* end function bubbleSort */ 159 160 /* output array contents (20 values per row) */ 161 void printArray( const int a[] ) 162 { 163 int j; /* counter */ 164 165 166 167 168 169 170 /* output array contents */ for ( j = 0; j < SIZE; j++ ) { if ( j % 20 == 0 ) { /* begin new line every 20 values */ printf( "\n" ); } /* end if */
(6 of 6 )
171 172 printf( "%2d", a[ j ] ); 173 } /* end for */ 174 175 } /* end function printArray */
******** 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 6 7 8 9 8 7 6 7 8 9 3 9 6 7 8 7 8 7 5 6 7 2 5 3 7 4 4 2 5 3 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
70
Outline
(1 of 2 )
array 8 9 8 8 7 8 9 8 9 9 4 6 8 7 5 of responses is 9 7 8 9 5 9 8 7 7 7 8 9 8 9 8 9 2 7 8 9 8 9 8 9 4 7 8 9 6 8 7 8 6 4 5 6 1 6 5 7 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
8 7 7 9 8 5 7 8 8 9
7 8 5 7 7 5 7 8 8 9
8 9 3 8
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
(continued from previous slide) The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** Response
71
Outline
Frequency
Histogram 1 0 1 5 2 0 2 5
(2 of 2 )
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.
72
Linear search
Simple Compare each element of array with key value Useful for small and unsorted arrays
1 2 3 4 5 6 7 8
/* Fig. 6.18: fig06_18.c Linear search of an array */ #include <stdio.h> #define SIZE 100 /* function prototype */ int linearSearch( const int array[], int key, int size );
73
Outline
fig06_18.c
9 /* function main begins program execution */ 10 int main( void ) 11 { 12 13 14 15 16 17 18 19 20 21 /* create data */ for ( x = 0; x < SIZE; x++ ) { a[ x ] = 2 * x; } /* end for */ int a[ SIZE ]; /* create array a */ int x; /* counter for initializing elements 0-99 of array a */ int searchKey; /* value to locate in array a */ int element; /* variable to hold location of searchKey or -1 */
(1 of 3 )
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
printf( "Enter integer search key:\n" ); scanf( "%d", &searchKey ); /* attempt to locate searchKey in array a */ element = linearSearch( a, searchKey, SIZE ); /* display results */ if ( element != -1 ) { printf( "Found value in element %d\n", element ); } /* end if */ else { printf( "Value not found\n" ); } /* end else */ return 0; /* indicates successful termination */
74
Outline
fig06_18.c
(2 of 3 )
37 38 } /* end main */ 39 40 /* compare key to every element of array until the location is found 41 or until the end of array is reached; return subscript of element 42 if key or -1 if key is not found */ 43 int linearSearch( const int array[], int key, int size ) 44 { 45 int n; /* counter */ 46
47 48 49 50 51 52 53 54 55 56 57
/* loop through array */ for ( n = 0; n < size; ++n ) { if ( array[ n ] == key ) { return n; /* return location of key */ } /* end if */ } /* end for */ return -1; /* key not found */
75
Outline
Linear search algorithm searches through every element in the array until a match is found
fig06_18.c
(3 of 3 )
58 } /* end function linearSearch */ Enter integer search key: 36 Found value in element 18
76
1 2 3 4 5 6 7 8 9 10 11 12
/* Fig. 6.19: fig06_19.c Binary search of an array */ #include <stdio.h> #define SIZE 15 /* function prototypes */ int binarySearch( const int b[], int searchKey, int low, int high ); void printHeader( void ); void printRow( const int b[], int low, int mid, int high ); /* function main begins program execution */ int main( void ) int int int int a[ SIZE ]; /* create array a */ i; /* counter for initializing elements 0-14 of array a */ key; /* value to locate in array a */ result; /* variable to hold location of key or -1 */
77
Outline
fig06_19.c
(1 of 6 )
13 { 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
/* create data */ for ( i = 0; i < SIZE; i++ ) { a[ i ] = 2 * i; } /* end for */ printf( "Enter a number between 0 and 28: " ); scanf( "%d", &key ); printHeader(); /* search for key in array a */ result = binarySearch( a, key, 0, SIZE - 1 );
31 32 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
78
/* display results */ if ( result != -1 ) { printf( "\n%d found in array element %d\n", key, result ); } /* end if */ else { printf( "\n%d not found\n", key ); } /* end else */ return 0; /* indicates successful termination */ } /* end main */ /* function to perform binary search of an array */ int binarySearch( const int b[], int searchKey, int low, int high ) { int middle; /* variable to hold middle element of array */ /* loop until low subscript is greater than high subscript */ while ( low <= high ) { /* determine middle element of subarray being searched */ middle = ( low + high ) / 2; /* display subarray used in this loop iteration */ printRow( b, low, middle, high );
Outline
fig06_19.c
(2 of 6 )
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
/* if searchKey matched middle element, return middle */ if ( searchKey == b[ middle ] ) { return middle; } /* end if */
79
Outline
/* if searchKey less than middle element, set new high */ else if ( searchKey < b[ middle ] ) { high = middle - 1; /* search low end of array */ } /* end else if */
fig06_19.c
(3 of 6 )
75 return -1; /* searchKey not found */ 76 77 } /* end function binarySearch */ 78 79 /* Print a header for the output */ 80 void printHeader( void ) 81 { 82 83 84 85 int i; /* counter */ printf( "\nSubscripts:\n" );
86 87 88 89 90 91 92 93 94 95 96 97
/* output column head */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d ", i ); } /* end for */ printf( "\n" ); /* start new line of output */ /* output line of - characters */ for ( i = 1; i <= 4 * SIZE; i++ ) { printf( "-" ); } /* end for */
80
Outline
fig06_19.c
(4 of 6 )
98 printf( "\n" ); /* start new line of output */ 99 } /* end function printHeader */ 100 101 /* Print one row of output showing the current 102 part of the array being processed. */ 103 void printRow( const int b[], int low, int mid, int high ) 104 { 105 int i; /* counter for iterating through array b */ 106
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
/* loop through entire array */ for ( i = 0; i < SIZE; i++ ) { /* display spaces if outside current subarray range */ if ( i < low || i > high ) { printf( " " ); } /* end if */ else if ( i == mid ) { /* display middle element */ printf( "%3d*", b[ i ] ); /* mark middle value */ } /* end else if */ else { /* display other elements in subarray */ printf( "%3d ", b[ i ] ); } /* end else */ } /* end for */ printf( "\n" ); /* start new line of output */
81
Outline
fig06_19.c
(5 of 6 )
124 } /* end function printRow */ Enter a number between 0 and 28: 25 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 16 18 20 22* 24 26 28 24 26* 28 24* 25 not found (continued on next slide )
(continued from previous slide) Enter a number between 0 and 28: 8 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 8 10* 12 8* 8 found in array element 4
82
Outline
fig06_19.c
(6 of 6 )
Enter a number between 0 and 28: 6 Subscripts: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -----------------------------------------------------------0 2 4 6 8 10 12 14* 16 18 20 22 24 26 28 0 2 4 6* 8 10 12 6 found in array element 3
83
Initialization
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
Initializers grouped by row in braces If not enough, unspecified elements set to zero
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Referencing elements
Specify row, then column
printf( "%d", b[ 0 ][ 1 ] );
84
85
Fig. 6.20 | Double-subscripted array with three rows and four columns.
1 2 3 4 5 6 7 8
/* Fig. 6.21: fig06_21.c Initializing multidimensional arrays */ #include <stdio.h> void printArray( const int a[][ 3 ] ); /* function prototype */ /* function main begins program execution */ int main( void ) /* initialize array1, array2, array3 */ int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; printf( "Values in array1 by row are:\n" ); printArray( array1 ); printf( "Values in array2 by row are:\n" ); printArray( array2 ); printf( "Values in array3 by row are:\n" ); printArray( array3 );
86
Outline
fig06_21.c
9 { 10 11 12 13 14 15 16 17 18 19 20 21 22 23
28 /* function to output array with two rows and three columns */ 29 void printArray( const int a[][ 3 ] ) 30 { 31 32 33 34 35 36 37 38 39 40 41 42 43 44 int i; /* row counter */ int j; /* column counter */ /* loop through rows */ for ( i = 0; i <= 1; i++ ) { /* output column values */ for ( j = 0; j <= 2; j++ ) { printf( "%d ", a[ i ][ j ] ); } /* end inner for */ printf( "\n" ); /* start new line of output */ } /* end outer for */
87
Outline
fig06_21.c
(2 of 2 )
45 } /* end function printArray */ Values in array1 by row are: 1 2 3 4 5 6 Values in array2 by row are: 1 2 3 4 5 0 Values in array3 by row are: 1 2 0 4 0 0
1 2 3 4 5 6 7 8
/* Fig. 6.22: fig06_22.c Double-subscripted array example */ #include <stdio.h> #define STUDENTS 3 #define EXAMS 4 /* function prototypes */ int minimum( const int grades[][ EXAMS ], int pupils, int tests );
88
Outline
fig06_22.c
9 int maximum( const int grades[][ EXAMS ], int pupils, int tests ); 10 double average( const int setOfGrades[], int tests ); 11 void printArray( const int grades[][ EXAMS ], int pupils, int tests ); 12 13 /* function main begins program execution */ 14 int main( void ) 15 { 16 int student; /* student counter */ 17 18 /* initialize student grades for three students (rows) */ 19 20 21 22 23 24 25 26 27 const int studentGrades[ STUDENTS ][ EXAMS ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; /* output array studentGrades */ printf( "The array is:\n" ); printArray( studentGrades, STUDENTS, EXAMS );
(1 of 6 )
28 29 30 31 32 33 34 35 36 37 38
/* determine smallest and largest grade values */ printf( "\n\nLowest grade: %d\nHighest grade: %d\n", minimum( studentGrades, STUDENTS, EXAMS ), maximum( studentGrades, STUDENTS, EXAMS ) ); /* calculate average grade for each student */ for ( student = 0; student < STUDENTS; student++ ) { printf( "The average grade for student %d is %.2f\n", student, average( studentGrades[ student ], EXAMS ) ); } /* end for */
89
Outline
fig06_22.c
(2 of 6 )
43 /* Find the minimum grade */ 44 int minimum( const int grades[][ EXAMS ], int pupils, int tests ) 45 { 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 int i; /* student counter */ int j; /* exam counter */ int lowGrade = 100; /* initialize to highest possible grade */ /* loop through rows of grades */ for ( i = 0; i < pupils; i++ ) { /* loop through columns of grades */ for ( j = 0; j < tests; j++ ) { if ( grades[ i ][ j ] < lowGrade ) { lowGrade = grades[ i ][ j ]; } /* end if */ } /* end inner for */ } /* end outer for */
90
Outline
fig06_22.c
(3 of 6 )
68 /* Find the maximum grade */ 69 int maximum( const int grades[][ EXAMS ], int pupils, int tests ) 70 { 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 int i; /* student counter */ int j; /* exam counter */ int highGrade = 0; /* initialize to lowest possible grade */ /* loop through rows of grades */ for ( i = 0; i < pupils; i++ ) { /* loop through columns of grades */ for ( j = 0; j < tests; j++ ) { if ( grades[ i ][ j ] > highGrade ) { highGrade = grades[ i ][ j ]; } /* end if */ } /* end inner for */ } /* end outer for */
91
Outline
fig06_22.c
(4 of 6 )
93 /* Determine the average grade for a particular student */ 94 double average( const int setOfGrades[], int tests ) 95 { 96 97 98 99 100 101 102 103 104 return ( double ) total / tests; /* average */ 105 106 } /* end function average */ 107 108 /* Print the array */ 109 void printArray( const int grades[][ EXAMS ], int pupils, int tests ) 110 { 111 int i; /* student counter */ 112 int j; /* exam counter */ 113 114 115 116 /* output column heads */ printf( " [0] [1] [2] [3]" ); /* total all grades for one student */ for ( i = 0; i < tests; i++ ) { total += setOfGrades[ i ]; } /* end for */ int i; /* exam counter */ int total = 0; /* sum of test grades */
92
Outline
fig06_22.c
(5 of 6 )
117 118 119 120 121 122 123 124 125 126 127 128
/* output grades in tabular format */ for ( i = 0; i < pupils; i++ ) { /* output label for row */ printf( "\nstudentGrades[%d] ", i ); /* output grades for one student */ for ( j = 0; j < tests; j++ ) { printf( "%-5d", grades[ i ][ j ] ); } /* end inner for */ } /* end outer for */
93
Outline
fig06_22.c
(6 of 6 )
129 130 } /* end function printArray */ 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