Chapter 5 - Functions! 0 6 ;: > E 5J7J 5J 5J! 5J #"%$& ' ( )+*, -. / * - # * - # 213 45 * - # 7 )98 < = *?' )A@B?' )+C 4; D - C/ =(GF 'H I D. K D L M N& K - (8 C C -( O C -( O P7 7Q R S+T?U V&WAXZY\[^]`_bacXde[fW Divide and conquer Construct a program from smaller pieces or components Each piece more manageable than the original program 1
Functions S+Thg i%yj[^k`yjl`m no[^]p_rqesctd5wvu Modules in C Programs written by combining user-defined functions with library functions C standard library has a wide variety of functions Makes programmer's job easier - avoid reinventing the wheel Function calls Invoking functions Provide function name and arguments (data) Function performs operations or manipulations Function returns results Boss asks worker to complete task Worker gets information, does task, returns result Information hiding: boss does not know details S+Thw nxlyxz {9d.}~YjlpY\ _rwaa^xd;[ƒwat Math library functions perform common mathematical calculations #include <math.h> Format for calling functions FunctionName (argument); If multiple arguments, use comma-separated list printf( "%.2f", sqrt( 900.0 ) ); Calls function sqrt, which returns the square root of its argument All math functions return data type double Arguments may be constants, variables, or expressions 2
S+Th _rwaa^xd;[ƒwat Functions Modularize a program All variables declared inside functions are local variables Known only in function defined Parameters Communicate information between functions Local variables Benefits Divide and conquer Manageable program development Software reusability Use existing functions as building blocks for new programs Abstraction - hide internal details (library functions) Avoids code repetition S+T S _rwaa^xde[ƒw ˆsc d W d;xde[ƒwat Function definition format return-value-type function-name( parameter-list ) { declarations and statements } Function-name: any valid identifier Return-value-type: data type of the result (default int) void - function returns nothing Parameter-list: comma separated list, declares parameters (default int) 3
S+T S _rwaašxde[ƒw ˆsc d W d;xde[ƒwat,v&v Œ Function definition format (continued) return-value-type function-name( parameter-list ) { declarations and statements } Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested) Function can not be defined inside another function Returning control If nothing returned return; or, until reaches right brace If something returned return expression; 1 /* Fig. 5.4: fig05_04.c 2 Finding the maximum of three integers */ 3 #include <stdio.h> 4 5 int maximum( int, int, int ); /* function prototype */ 6 7 int main() 8 { 9 int a, b, c; 10 11 printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); 14 15 return 0; 16 } 17 18 /* Function maximum definition */ 19 int maximum( int x, int y, int z ) 20 { 21 int max = x; 22 23 if ( y > max ) 24 max = y; 25 26 if ( z > max ) 27 max = z; 28 29 return max; 30 } Enter three integers: 22 85 17 Maximum is: 85 / L &Õ Oš œ žh Ÿ, ;ž7 ž7?ÿ7 Ÿ, 7R 7 A H H ; # Lª ZŸHÕ?«/, Õ H, ± Õ OšH œ ž ² \Õ OšH œ ž ³, 7 œ Oœ œ ž /ežhµhe H ƒ Õ Ÿ,Õ 4
S+T _rwaa^xde[ƒw i%y\[^x±[cx±šŗsct Function prototype Function name Parameters - what the function takes in Return type - data type function returns (default int) Used to validate functions Prototype only needed if function definition comes after use in program int maximum( int, int, int ); Takes in 3 ints Returns an int Promotion rules and conversions Converting to lower types can lead to errors S+TN¹ º»scl~]ys¼Y½ d.q;sct Header files contain function prototypes for library functions <stdlib.h>, <math.h>, etc Load with #include <filename> #include <math.h> Custom header files Create file with functions Save as filename.h Load in other files with #include "filename.h" Reuse functions 5
S+T ¾ ul`q5q.d Wk _rwaacxodr[¼watáà uglpq.q}rãâälpq._as l`wa]åulpq.q}rçæèsc NsfYjsƒWAa^s Used when invoking functions Call by value Copy of argument passed to function Changes in function do not effect original Use when function does not need to modify argument Avoids accidental changes Call by reference Passes original argument Changes in function effect original Only used with trusted functions For now, we focus on call by value S+T É ÆlpWA]y[¼m ÊË_rmÅ}rs¼YMÌxs¼WAs¼Yjl~Xd;[¼W rand function Load <stdlib.h> Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); Pseudorandom Preset sequence of "random" numbers Same sequence every time program is executed Scaling To get a random number between 1 and n 1 + ( rand() % n ) rand % n returns a number between 0 and n-1 Add 1 to make random number between 1 and n 1 + ( rand() % 6) /* number between 1 and 6 */ 6
S+T É ÆlpWA]~[fm ÊË_rmÅ}½sfY%ÌÍs¼WAs¼Yjl~Xd;[¼W,V&V Œ srand function <stdlib.h> Takes an integer seed - jumps to location in "random" sequence srand( seed ); srand( time( NULL ) ); /* load <time.h> */ time( NULL )- time program was compiled in seconds "randomizes" the seed 1 /* Fig. 5.9: fig05_09.c 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 int main() 7 { 8 int i; 9 unsigned seed; 10 11 printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { 16 printf( "%10d", 1 + ( rand() % 6 ) ); / Lª Zœ œ 7 œ Î# H ³ Lª ZŸHÕ?«/, Õ ž7o # H³ Ï7 srand ž š7ðo, OµH ;, O³,ž7. HÑ,Õ Zš7 cò H œ O Ó ž7žhÿ H LÔ 7 O H ;,, O³ ž7õ ŸHÕ? ;, O³HžH OÕ bõh 7R 17 18 if ( i % 5 == 0 ) 19 printf( "\n" ); 20 } 21 22 return 0; 23 } 2000 Prentice Hall, Inc. All rights reserved. 7
Enter seed: 67 6 1 4 6 2 1 6 1 6 4 Enter seed: 867 2 4 6 1 6 1 1 3 6 2 /ežhµhe H ƒ Õ Ÿ,Õ Enter seed: 67 6 1 4 6 2 1 6 1 6 4 S+T?Ū Ö BØ%l`mÙ Úq;s¼À ÛÜÌxlpm sý[c %uízalpwaacs Craps simulator Rules Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point" Player must roll his point before rolling 7 to win Player loses if he rolls 7 before rolling his point 8
1 /* Fig. 5.10: fig05_10.c 2 Craps */ 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 int rolldice( void ); 8 9 int main() 10 { 11 int gamestatus, sum, mypoint; 12 13 srand( time( NULL ) ); 14 sum = rolldice(); /* first roll of the dice */ 15 16 switch ( sum ) { 17 case 7: case 11: /* win on first roll */ 18 gamestatus = 1; 19 break; 20 case 2: case 3: case 12: /* lose on first roll */ 21 gamestatus = 2; 22 break; 23 default: /* remember point */ 24 gamestatus = 0; 25 mypoint = sum; 26 printf( "Point is %d\n", mypoint ); 27 break; 28 } 29 30 while ( gamestatus == 0 ) { /* keep rolling */ 31 sum = rolldice(); 32 / ŸHež7 ž7 ŸH rolldice / ª Oœ œ, œ Îj «, ;œ,õ, 7 / cþ 7 H³ srand Ò œ O switch., H b 7 Z ž7 ß œ Oà\ ž7 àjšhž Z œ Õ =Ó#žžHŸ 33 if ( sum == mypoint ) /* win by making point */ 34 gamestatus = 1; 35 else 36 if ( sum == 7 ) /* lose by rolling 7 */ 37 gamestatus = 2; 38 } 39 40 if ( gamestatus == 1 ) 41 printf( "Player wins\n" ); 42 else 43 printf( "Player loses\n" ); 44 45 return 0; 46 } 47 48 int rolldice( void ) 49 { 50 int die1, die2, worksum; 51 52 die1 = 1 + ( rand() % 6 ); 53 die2 = 1 + ( rand() % 6 ); 54 worksum = die1 + die2; 55 printf( "Player rolled %d + %d = %d\n", die1, die2, worksum ); 56 return worksum; 57 } Player rolled 6 + 5 = 11 Player wins eœ O ß œ Oà\ ž7 /ežhµhe H ƒ Õ Ÿ,Õ 9
Player rolled 6 + 6 = 12 Player loses Player rolled 4 + 6 = 10 Point is 10 Player rolled 2 + 4 = 6 Player rolled 6 + 5 = 11 Player rolled 3 + 3 = 6 Player rolled 6 + 4 = 10 Player wins /ežhµhe H ƒ Õ Ÿ,Õ Player rolled 1 + 3 = 4 Point is 4 Player rolled 1 + 4 = 5 Player rolled 5 + 4 = 9 Player rolled 4 + 6 = 10 Player rolled 6 + 3 = 9 Player rolled 1 + 2 = 3 Player rolled 5 + 2 = 7 Player loses S+TOU%UâáÈX±[ƒY#l~kysÇuÍqelyt t sct Storage class specifiers Storage duration - how long an object exists in memory Scope - where object can be referenced in program Linkage - what files an identifier is known (more in Chapter 14) Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; register: tries to put variable into high-speed registers Can only be used for automatic variables register int counter = 1; 10
S+TOU%UâáÈX±[ƒYjlyk~sÝuÍqelytãt9sct,V&V Œ Static storage Variables exist for entire program execution Default value of zero static: local variables defined in functions. Keep value after function ends Only known in their own function. extern: default for global variables and functions. Known in any function S+TOŪ g áèac[¼ŗsäæå_rqesct File scope Identifier defined outside function, known in all functions Global variables, function definitions, function prototypes Function scope Can only be referenced inside a function body Only labels (start: case:, etc.) 11
S+TOŪ g áèac[¼ŗsäæå_rqesct,v&v Œ Block scope Identifier declared inside a block Block scope begins at declaration, ends at right brace Variables, function parameters (local variables of function) Outer blocks "hidden" from inner blocks if same variable name Function prototype scope Identifiers in parameter list Names in function prototype optional, and can be used anywhere 1 /* Fig. 5.12: fig05_12.c 2 A scoping example */ 3 #include <stdio.h> 4 5 void a( void ); /* function prototype */ 6 void b( void ); /* function prototype */ 7 void c( void ); /* function prototype */ 8 9 int x = 1; /* global variable */ 10 11 int main() 12 { 13 int x = 5; /* local variable to main */ 14 15 printf("local x in outer scope of main is %d\n", x ); 16 17 { /* start new scope */ 18 int x = 7; 19 20 printf( "local x in inner scope of main is %d\n", x ); 21 } /* end new scope */ 22 23 printf( "local x in outer scope of main is %d\n", x ); 24 25 a(); /* a has automatic local x */ 26 b(); /* b has static local x */ 27 c(); /* c uses global x */ 28 a(); /* a reinitializes automatic local x */ 29 b(); /* static local x retains its previous value */ 30 2000 c(); Prentice Hall, Inc. /* All global rights reserved. x also retains its value */ / L &Õ Oš œ žh Ÿ, ;ž7 ž7?ÿ7 H / ª Oœ œ, œ Îj µh ž7õ, H «/,eœ HÕ, / ª Oœ œ, œ Îj žšh, «/,eœ HÕ, / cª Oœ œ, œ Îj žšh, «/,eœ HÕ, œ æõ, ž7š7ç L ã, ± Õ š œ žh O H L Õ ŸHÕ e 7 Z 12
31 32 printf( "local x in main is %d\n", x ); 33 return 0; 34 } 35 36 void a( void ) 37 { 38 int x = 25; /* initialized each time a is called */ 39 40 printf( "\nlocal x in a is %d after entering a\n", x ); 41 ++x; 42 printf( "local x in a is %d before exiting a\n", x ); 43 } 44 45 void b( void ) 46 { 47 static int x = 50; /* static initialization only */ 48 /* first time b is called */ 49 printf( "\nlocal static x is %d on entering b\n", x ); 50 ++x; 51 printf( "local static x is %d on exiting b\n", x ); 52 } 53 54 void c( void ) 55 { 56 printf( "\nglobal x is %d on entering c\n", x ); 57 x *= 10; 58 printf( "global x is %d on exiting c\n", x ); 59 } 2000 Prentice Hall, Inc. All rights reserved. H = \Õ OšH œ žh ³7 H œ Oœ œ žh O local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a /ežhµhe H ƒ Õ Ÿ,Õ local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5 13
S+T?Ū w Æs^aƒ_ Yjtæde[¼W Recursive functions Function that calls itself Can only solve a base case Divides up problem into What it can do What it cannot do - resembles original problem Launches a new copy of itself (recursion step) Eventually base case gets solved Gets plugged in, works its way up and solves whole problem S+T?Ū w Æs^aƒ_ Yjtæde[¼W,V&V Œ Example: factorial: 5! = 5 * 4 * 3 * 2 * 1 Notice that 5! = 5 * 4! 4! = 4 * 3!... Can compute factorials recursively Solve base case (1! = 0! = 1) then plug in 2! = 2 * 1! = 2 * 1 = 2; 3! = 3 * 2! = 3 * 2 = 6; 14
S+T?Ū BØ%l`mÙ Úq;séèåt d5wak Æsca¼_rYjtÁde[ƒWrÀ ê zasë d.}r[ƒwal~a^aƒddáèsƒy/desct Fibonacci series: 0, 1, 1, 2, 3, 5, 8... Each number sum of the previous two fib(n) = fib(n-1) + fib(n-2) - recursive formula long fibonacci(long n) { if (n==0 n==1) //base case return n; else return fibonacci(n-1) + fibonacci(n-2); } S+T?Ū BØ%l`mÙ Úq;séèåt d5wak Æsca¼_rYjtÁde[ƒWrÀ ê zasé d5}½[ƒwalya^aƒddáèsƒyd;sct,v&v Œ f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) + f( 0 ) return 1 return 1 return 0 15
1 /* Fig. 5.15: fig05_15.c 2 Recursive fibonacci function */ 3 #include <stdio.h> 4 5 long fibonacci( long ); 6 7 int main() 8 { 9 long result, number; 10 11 printf( "Enter an integer: " ); 12 scanf( "%ld", &number ); 13 result = fibonacci( number ); 14 printf( "Fibonacci( %ld ) = %ld\n", number, result ); 15 return 0; 16 } 17 18 /* Recursive definition of function fibonacci */ 19 long fibonacci( long n ) 20 { 21 if ( n == 0 n == 1 ) 22 return n; 23 else 24 return fibonacci( n - 1 ) + fibonacci( n - 2 ); 25 } Enter an integer: 0 Fibonacci(0) = 0 / L &Õ Oš œ žh Ÿ, ;ž7 ž7?ÿ7 / ª Oœ œ, œ Îj «, ;œ,õ, 7 Lª ZŸHÕ? H œ O 7µ, 7, ± Õ OšH œ ž fibonacci Z Ÿ,Õ? ; 7 Õ ì H Ò œ O ; 7šHÕ; œ «7 /ežhµhe H ƒ Õ Ÿ,Õ fibonacci Enter an integer: 1 Fibonacci(1) = 1 Enter an integer: 2 Fibonacci(2) = 1 Enter an integer: 3 Fibonacci(3) = 2 Enter an integer: 4 Fibonacci(4) = 3 /ežhµhe H ƒ Õ Ÿ,Õ Enter an integer: 5 Fibonacci(5) = 5 Enter an integer: 6 Fibonacci(6) = 8 Enter an integer: 10 Fibonacci(10) = 55 Enter an integer: 20 Fibonacci(20) = 6765 Enter an integer: 30 Fibonacci(30) = 832040 Enter an integer: 35 Fibonacci(35) = 9227465 16
S+T?Ū S Æs^aƒ_ Y\tÁdR[fWví%tÁT2V X±s¼Yjl~Xd;[¼W Repetition Iteration: explicit loop Recursion: repeated function calls Termination Iteration: loop condition fails Recursion: base case recognized Both can have infinite loops Balance Choice between performance (iteration) and good software engineering (recursion) Chapter 6 - Arrays îrïhð\ñ ò ólô 65J 6 6! 6 0 6 66 6;: 6> 6E Q -. õbö =) 13 -D rõbö L) \ø7r8 ÈùZO rõaú =) ± \O ½õö L) D ˆ* -. K (. ½õö L) (½8. ~,û y ˆùZO rõaú =) K -D" rõbö L),. 8 (ü K 'H\- 8 R +õú L) 17
+T?U V&WAXZY\[Š]ý_bacXd;[¼W Arrays Structures of related data items Static entity - same size throughout program Dynamic data structures discussed in Chapter 12 +Thg ÛþYYjl~ÿt Array Group of consecutive memory locations Same name and type Name of array (Note that all elements of this array have the same name, c) To refer to an element, specify Array name Position number Format: arrayname[position number] First element at position 0 n element array named c: c[0], c[1]...c[n-1] c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] -45 6 0 72 1543-89 0 62-3 1 6453 78 Position number of the element within array c 18
+Thg ÛþYYjl~ÿtG,V&VhŒ Array elements are like normal variables c[0] = 3; printf( "%d", c[0] ); Perform operations in subscript. If x = 3, c[5-2] == c[3] == c[x] +Thw cs^aƒq;l`y/d WbkÅÛ YYjl~åt When declaring arrays, specify Name Type of array Number of elements arraytype arrayname[ numberofelements ]; int c[ 10 ]; float myarray[ 3284 ]; Declaring multiple arrays of same type Format similar to regular variables int b[ 100 ], x[ 27 ]; 19
+Th BØ%l`mÙ Úq;s^tGèÿtæd.WbkÅÛ Y/Y\ly t Initializers int n[5] = {1, 2, 3, 4, 5 }; If not enough initializers, rightmost elements become 0 If too many, syntax error int n[5] = {0} All elements 0 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 1 /* Fig. 6.8: fig06_08.c 2 Histogram printing program */ 3 #include <stdio.h> 4 #define SIZE 10 5 6 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; 10 11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); 12 13 for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( "%7d%13d ", i, n[ i ]) ; 15 16 for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( "%c", * ); 18 19 printf( "\n" ); 20 } 21 22 return 0; 23 } / \ª Oœ œ, œ Îj, ;R 7 LÓ žhžÿ H \ /eœ O 20
Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 * /ežhµhe H ƒ Õ Ÿ,Õ +T BØ%lýmÇ ÚqesŠtGèÿt d5wbkåû YYjl~ÿt,VNVhŒ Character arrays String "hello" is really a static array of characters Character arrays can be initialized using string literals char string1[] = "first"; null character \0 terminates strings string1 actually has 6 elements char string1[] = { f, i, r, s, t, \0 }; 21
+Th BØ%l`mÙ Úq;s^tGèÿtæd.WbkÅÛ Y/Y\ly t,v&vnvhœ Character arrays (continued) Access individual characters string1[ 3 ] is character s Array name is address of array, so & not needed for scanf scanf( "%s", string2 ) ; Reads characters until whitespace encountered Can write beyond end of array, be careful 1 /* Fig. 6.10: fig06_10.c 2 Treating character arrays as strings */ 3 #include <stdio.h> 4 5 int main() 6 { 7 char string1[ 20 ], string2[] = "string literal"; 8 int i; 9 10 printf(" Enter a string: "); 11 scanf( "%s", string1 ); 12 printf( "string1 is: %s\nstring2: is %s\n" 13 "string1 with spaces between characters is:\n", 14 string1, string2 ); 15 16 for ( i = 0; string1[ i ]!= \0 ; i++ ) 17 printf( "%c ", string1[ i ] ); 18 19 printf( "\n" ); 20 return 0; 21 } Enter a string: Hello there string1 is: Hello string2 is: string literal string1 with spaces between characters is: H e l 2000 l oprentice Hall, Inc. All rights reserved. / Lª Zœ œ 7 œ Î# ;œ Oµ, L eœ O # eœ Oµ, Ò H œ O žhž7ÿ eœ O?š7ÐO He,š H ; œ O³,œ «œ ³HÕ H cª OŸHÕ # eœ Oµ H L eœ O # eœ Oµ /ežhµhe H ƒ Õ Ÿ,Õ 22
+T S iælytãtád.wakåû Y/Y\lyÿtýX±[ë _rwaa^xde[ƒwbt Passing arrays Specify array name without brackets int myarray[ 24 ]; myfunction( myarray, 24 ); Array size usually passed to function Arrays passed call-by-reference Name of array is address of first element Function knows where the array is stored Modifies original memory locations Passing array elements Passed by call-by-value Pass subscripted name (i.e., myarray[3]) to function +T S iæl~t tád.wakåû YYjl~åtýX±[é _rwaa^xd;[ƒwbtg,v&v Œ Function prototype void modifyarray( int b[], int arraysize ); Parameter names optional in prototype int b[] could be simply int [] int arraysize could be simply int 23
1 /* Fig. 6.13: fig06_13.c 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 5 5 6 void modifyarray( int [], int ); /* appears strange */ 7 void modifyelement( int ); 8 9 int main() 10 { 11 int a[ SIZE ] = { 0, 1, 2, 3, 4 }, i; 12 13 printf( "Effects of passing entire array call " 14 "by reference:\n\nthe values of the " 15 "original array are:\n" ); 16 17 for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( "%3d", a[ i ] ); 19 20 printf( "\n" ); 21 modifyarray( a, SIZE ); /* passed call by reference */ 22 printf( "The values of the modified array are:\n" ); 23 24 for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( "%3d", a[ i ] ); 26 27 printf( "\n\n\neffects of passing array element call " 28 "by value:\n\nthe value of a[3] is %d\n", a[ 3 ] ); 29 modifyelement( a[ 3 ] ); 30 printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); 31 return 0; 32 } 2000 Prentice Hall, Inc. All rights reserved. / \ \Õ OšH œ ž ³, 7 œ Oœ œ ž O \ /,, ;R H Á ž Õ OšH œ ž7 = H, ; ;, H H H O ž b Z Oš7 œ ž7 H \ /eœ O Entire arrays passed call-byreference, and can be modified Array elements passed call-byvalue, and cannot be modified 33 34 void modifyarray( int b[], int size ) 35 { 36 int j; 37 38 for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 41 42 void modifyelement( int e ) 43 { 44 printf( "Value in modifyelement is %d\n", e *= 2 ); 45 } Effects of passing entire array call by reference: H = \Õ OšH œ žh ³7 H œ Oœ œ žh O /ežhµhe H ƒ Õ Ÿ,Õ The values of the original array are: 0 1 2 3 4 The values of the modified array are: 0 2 4 6 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 24
+Th áè[ƒy#xd.wakåû Y/Y\lyÿt Sorting data Important computing application Virtually every organization must sort some data Massive amounts must be sorted 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 +T&¹ ulytãs áèx_a]~^à ug[fmå ~_AXd5WAk nxs^l`w nxsc]pdelpwvlpwb] no[^]yséè tád.wakåû Y/Y\lyÿt Mean - average Median - number in middle of sorted list 1, 2, 3, 4, 5 3 is the median Mode - number that occurs most often 1, 1, 1, 2, 3, 3, 4, 5 1 is the mode 25
1 /* Fig. 6.16: fig06_16.c 2 This program introduces the topic of survey data analysis. 3 It computes the mean, median, and mode of the data */ 4 #include <stdio.h> 5 #define SIZE 99 6 7 void mean( const int [] ); 8 void median( int [] ); 9 void mode( int [], const int [] ) ; 10 void bubblesort( int [] ); 11 void printarray( const int [] ); 12 13 int main() 14 { 15 int frequency[ 10 ] = { 0 }; 16 int response[ SIZE ] = 17 { 6, 7, 8, 9, 8, 7, 8, 9, 8, 9, 18 7, 8, 9, 5, 9, 8, 7, 8, 7, 8, 19 6, 7, 8, 9, 3, 9, 8, 7, 8, 7, 20 7, 8, 9, 8, 9, 8, 9, 7, 8, 9, 21 6, 7, 8, 7, 8, 7, 9, 8, 9, 2, 22 7, 8, 9, 8, 9, 8, 9, 7, 5, 3, 23 5, 6, 7, 2, 5, 3, 9, 4, 6, 4, 24 7, 8, 9, 6, 8, 7, 8, 9, 7, 8, 25 7, 4, 4, 2, 5, 3, 8, 7, 5, 6, 26 4, 5, 6, 1, 6, 5, 7, 8, 7 }; 27 28 mean( response ); 29 median( response ); 30 mode( frequency, response ); 31 return 0; 32 } 2000 Prentice Hall, Inc. All rights reserved. / L &Õ Oš œ žh Ÿ, ;ž7 ž7?ÿ7 H / ª Oœ œ, œ Îj Hee, L ã, ± Õ š œ žh O mean median, O³ mode 33 34 void mean( const int answer[] ) 35 { 36 int j, total = 0; 37 38 printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); 39 40 for ( j = 0; j <= SIZE - 1; j++ ) 41 total += answer[ j ]; 42 43 printf( "The mean is the average value of the data\n" 44 "items. The mean is equal to the total of\n" 45 "all the data items divided by the number\n" 46 "of data items ( %d ). The mean value for\n" 47 "this run is: %d / %d = %.4f\n\n", 48 SIZE, total, SIZE, ( double ) total / SIZE ); 49 } 50 51 void median( int answer[] ) 52 { 53 printf( "\n%s\n%s\n%s\n%s", 54 "********", " Median", "********", 55 "The unsorted array of responses is" ); 56 57 printarray( answer ); 58 bubblesort( answer ); 59 printf( "\n\nthe sorted array is" ); 60 printarray( answer ); 61 printf( "\n\nthe median is element %d of\n" 62 "the sorted %d element array.\n" 63 "For this run the median is %d\n\n", 64 2000 Prentice SIZE Hall, Inc. / 2, All rights SIZE, reserved. answer[ SIZE / 2 ] ); H Ò œ O b Õ Oš7 œ žh mean H Ò H œ O Õ Oš7 œ ž7 median H Þ ž7e L ;;, H eœ O Aœ ³,³H 7 H H O 26
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 80 printf( "%s%11s%19s\n\n%54s\n%54s\n\n", 81 "Response", "Frequency", "Histogram", 82 "1 1 2 2", "5 0 5 0 5" ); 83 84 for ( rating = 1; rating <= 9; rating++ ) { 85 printf( "%8d%11d ", rating, freq[ rating ] ); 86 87 if ( freq[ rating ] > largest ) { 88 largest = freq[ rating ]; 89 modevalue = rating; 90 } 91 92 for ( h = 1; h <= freq[ rating ]; h++ ) 93 printf( "*" ); 94 H cò H œ O Õ Oš7 œ ž7 mode H Lª Zš7e, ³H 7Ÿ, 7 O³,œ Oµbž7 frequency[] response[] Notice how the subscript in frequency[] is the value of an element in response[] (answer[]) Print stars depending on value of frequency[] 95 printf( "\n" ); 96 } 97 98 printf( "The mode is the most frequent value.\n" 99 "For this run the mode is %d which occurred" 100 " %d times.\n", modevalue, largest ); 101} 102 103void bubblesort( int a[] ) 104{ 105 int pass, j, hold; 106 107 for ( pass = 1; pass <= SIZE - 1; pass++ ) 108 109 for ( j = 0; j <= SIZE - 2; j++ ) 110 111 if ( a[ j ] > a[ j + 1 ] ) { 112 hold = a[ j ]; 113 a[ j ] = a[ j + 1 ]; 114 a[ j + 1 ] = hold; 115 } 116} 117 118void printarray( const int a[] ) 119{ 120 int j; 121 122 for ( j = 0; j <= SIZE - 1; j++ ) { 123 124 if ( j % 20 == 0 ) 125 2000 Prentice printf( Hall, Inc. "\n" All rights ); reserved. H Ò H œ O bubblesort H Ò H œ O Bubble sort: if elements are out of order, swap them. printarray 27
126 127 printf( "%2d", a[ j ] ); 128 } 129} ******** 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 /ežhµhe H ƒ Õ Ÿ,Õ ******** 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 array is 1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** Response Frequency Histogram 1 1 2 2 5 0 5 0 5 /ežhµhe H ƒ Õ Ÿ,Õ 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. 28
+T ¾ áèscl`y#aƒzrd.wakåûþy/y\ly táà { d.wscl`yaás^lpy\a¼z l`wa] åd.walpy\ ás^lpy\afz Search an array for a key value Linear search Simple Compare each element of array with key value Useful for small and unsorted arrays +T ¾ áèscl`y#aƒzrd.wakåûþy/y\ly táà { d.wbsclpyaás^lpy\a¼z l`wa] åd.walpy\ ás^lpy\a¼z,vnvhœ 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 n Very fast; at most n steps, where 2 > number of elements 30 element array takes at most 5 steps 5 2 > 30 29
+ThÉ n _rq;xd. yqes 7áå_r}rt a¼y d5 ½X±s^]ÅÛþYYjl~ÿt Multiple subscripted arrays Tables with rows and columns (m by n array) Like matrices: specify row, then column Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column 3 a[0][0] a[1][0] a[2][0] a[0][1] a[1][1] a[2][1] a[0][2] a[1][2] a[2][2] a[0][3] a[1][3] a[2][3] Column subscript Array name Row subscript +ThÉ n _rq;xd. yqes 7áå_r}rt a¼y d5 ½X±s^]ÅÛþYYjl~ÿtG,V&VhŒ 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 } }; 1 2 3 4 1 0 3 4 Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 30
1 /* Fig. 6.22: fig06_22.c 2 Double-subscripted array example */ 3 #include <stdio.h> 4 #define STUDENTS 3 5 #define EXAMS 4 6 7 int minimum( const int [][ EXAMS ], int, int ); 8 int maximum( const int [][ EXAMS ], int, int ); 9 double average( const int [], int ); 10 void printarray( const int [][ EXAMS ], int, int ); 11 12 int main() 13 { exam. 14 int student; 15 const int studentgrades[ STUDENTS ][ EXAMS ] = 16 { { 77, 68, 86, 73 }, 17 { 96, 87, 89, 78 }, 18 { 70, 90, 86, 81 } }; 19 20 printf( "The array is:\n" ); 21 printarray( studentgrades, STUDENTS, EXAMS ); 22 printf( "\n\nlowest grade: %d\nhighest grade: %d\n", 23 minimum( studentgrades, STUDENTS, EXAMS ), 24 maximum( studentgrades, STUDENTS, EXAMS ) ); 25 26 for ( student = 0; student <= STUDENTS - 1; student++ ) 27 printf( "The average grade for student %d is %.2f\n", 28 student, 29 average( studentgrades[ student ], EXAMS ) ); 30 31 return 0; 32 } 2000 Prentice Hall, Inc. All rights reserved. / Lª Zœ œ 7 œ Î# «Heœ HÕH 7 / Ò H œ O Õ Oš7 œ ž7 O ž Hç ³HžH ÕH #šrœ Ÿ, H³ He ;, Each row is a particular student, each column is the grades on the / ª Oœ œ, œ Îj studentgrades[][] L ã, ± Õ š œ žh O H O³ minimum maximum average 33 34 /* Find the minimum grade */ 35 int minimum( const int grades[][ EXAMS ], 36 int pupils, int tests ) 37 { 38 int i, j, lowgrade = 100; 39 40 for ( i = 0; i <= pupils - 1; i++ ) 41 for ( j = 0; j <= tests - 1; j++ ) 42 if ( grades[ i ][ j ] < lowgrade ) 43 lowgrade = grades[ i ][ j ]; 44 45 return lowgrade; 46 } 47 48 /* Find the maximum grade */ 49 int maximum( const int grades[][ EXAMS ], 50 int pupils, int tests ) 51 { 52 int i, j, highgrade = 0; 53 54 for ( i = 0; i <= pupils - 1; i++ ) 55 for ( j = 0; j <= tests - 1; j++ ) 56 if ( grades[ i ][ j ] > highgrade ) 57 highgrade = grades[ i ][ j ]; 58 59 return highgrade; 60 } 61 62 /* Determine the average grade for a particular exam */ 63 double average( const int setofgrades[], int tests ) 64 { 2000 Prentice Hall, Inc. All rights reserved. H Ò œ O b Õ Oš7 œ žh O 31
65 int i, total = 0; 66 67 for ( i = 0; i <= tests - 1; i++ ) 68 total += setofgrades[ i ]; 69 70 return ( double ) total / tests; 71 } 72 73 /* Print the array */ 74 void printarray( const int grades[][ EXAMS ], 75 int pupils, int tests ) 76 { 77 int i, j; 78 79 printf( " [0] [1] [2] [3]" ); 80 81 for ( i = 0; i <= pupils - 1; i++ ) { 82 printf( "\nstudentgrades[%d] ", i ); 83 84 for ( j = 0; j <= tests - 1; j++ ) 85 printf( "%-5d", grades[ i ][ j ] ); 86 } 87 } H Ò œ O b Õ Oš7 œ žh O The array is: [0] [1] [2] [3] studentgrades[0] 77 68 86 73 studentgrades[1] 96 87 89 78 studentgrades[2] 70 90 86 81 /ežhµhe H ƒ Õ Ÿ,Õ 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 32