Chapter 5 - Functions

Size: px
Start display at page:

Download "Chapter 5 - Functions"

Transcription

1 Chapter 5 - Functions! 0 6 ;: > E 5J7J 5J 5J! 5J #"%$& ' ( )+*, -. / * - # * - # * - # 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

2 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( ) ); 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

3 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

4 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; printf( "Enter three integers: " ); 12 scanf( "%d%d%d", &a, &b, &c ); 13 printf( "Maximum is: %d\n", maximum( a, b, c ) ); return 0; 16 } /* Function maximum definition */ 19 int maximum( int x, int y, int z ) 20 { 21 int max = x; if ( y > max ) 24 max = y; if ( z > max ) 27 max = z; return max; 30 } Enter three integers: 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

5 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

6 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

7 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; printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); 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 if ( i % 5 == 0 ) 19 printf( "\n" ); 20 } return 0; 23 } 2000 Prentice Hall, Inc. All rights reserved. 7

8 Enter seed: Enter seed: /ežhµhe H ƒ Õ Ÿ,Õ Enter seed: 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

9 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; srand( time( NULL ) ); 14 sum = rolldice(); /* first roll of the dice */ 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 } 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 } if ( gamestatus == 1 ) 41 printf( "Player wins\n" ); 42 else 43 printf( "Player loses\n" ); return 0; 46 } int rolldice( void ) 49 { 50 int die1, die2, worksum; 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 = 11 Player wins eœ O ß œ Oà\ ž7 /ežhµhe H ƒ Õ Ÿ,Õ 9

10 Player rolled = 12 Player loses Player rolled = 10 Point is 10 Player rolled = 6 Player rolled = 11 Player rolled = 6 Player rolled = 10 Player wins /ežhµhe H ƒ Õ Ÿ,Õ Player rolled = 4 Point is 4 Player rolled = 5 Player rolled = 9 Player rolled = 10 Player rolled = 9 Player rolled = 3 Player rolled = 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

11 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

12 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 */ int main() 12 { 13 int x = 5; /* local variable to main */ printf("local x in outer scope of main is %d\n", x ); { /* start new scope */ 18 int x = 7; printf( "local x in inner scope of main is %d\n", x ); 21 } /* end new scope */ printf( "local x in outer scope of main is %d\n", x ); 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 */ 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

13 31 32 printf( "local x in main is %d\n", x ); 33 return 0; 34 } void a( void ) 37 { 38 int x = 25; /* initialized each time a is called */ 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 } 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 } 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

14 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

15 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

16 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; printf( "Enter an integer: " ); 12 scanf( "%ld", &number ); 13 result = fibonacci( number ); 14 printf( "Fibonacci( %ld ) = %ld\n", number, result ); 15 return 0; 16 } /* 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) = Enter an integer: 35 Fibonacci(35) =

17 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> 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

18 +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] Position number of the element within array c 18

19 +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

20 +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 int main() 7 { 8 int n[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 9 int i, j; printf( "%s%13s%17s\n", "Element", "Value", "Histogram" ); for ( i = 0; i <= SIZE - 1; i++ ) { 14 printf( "%7d%13d ", i, n[ i ]) ; for ( j = 1; j <= n[ i ]; j++ ) /* print one bar */ 17 printf( "%c", * ); printf( "\n" ); 20 } return 0; 23 } / \ª Oœ œ, œ Îj, ;R 7 LÓ žhžÿ H \ /eœ O 20

21 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

22 +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 ); for ( i = 0; string1[ i ]!= \0 ; i++ ) 17 printf( "%c ", string1[ i ] ); 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

23 +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

24 1 /* Fig. 6.13: fig06_13.c 2 Passing arrays and individual array elements to functions */ 3 #include <stdio.h> 4 #define SIZE 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; printf( "Effects of passing entire array call " 14 "by reference:\n\nthe values of the " 15 "original array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) 18 printf( "%3d", a[ i ] ); printf( "\n" ); 21 modifyarray( a, SIZE ); /* passed call by reference */ 22 printf( "The values of the modified array are:\n" ); for ( i = 0; i <= SIZE - 1; i++ ) 25 printf( "%3d", a[ i ] ); 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 void modifyarray( int b[], int size ) 35 { 36 int j; for ( j = 0; j <= size - 1; j++ ) 39 b[ j ] *= 2; 40 } 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: The values of the modified array are: 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

25 +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: pass 1: pass 2: 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

26 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 void mean( const int [] ); 8 void median( int [] ); 9 void mode( int [], const int [] ) ; 10 void bubblesort( int [] ); 11 void printarray( const int [] ); 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 }; 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 void mean( const int answer[] ) 35 { 36 int j, total = 0; printf( "%s\n%s\n%s\n", "********", " Mean", "********" ); for ( j = 0; j <= SIZE - 1; j++ ) 41 total += answer[ j ]; 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 } void median( int answer[] ) 52 { 53 printf( "\n%s\n%s\n%s\n%s", 54 "********", " Median", "********", 55 "The unsorted array of responses is" ); 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", 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

27 65 } void mode( int freq[], const int answer[] ) 68 { 69 int rating, j, h, largest = 0, modevalue = 0; printf( "\n%s\n%s\n%s\n", 72 "********", " Mode", "********" ); for ( rating = 1; rating <= 9; rating++ ) 75 freq[ rating ] = 0; for ( j = 0; j <= SIZE - 1; j++ ) 78 ++freq[ answer[ j ] ]; printf( "%s%11s%19s\n\n%54s\n%54s\n\n", 81 "Response", "Frequency", "Histogram", 82 " ", " " ); for ( rating = 1; rating <= 9; rating++ ) { 85 printf( "%8d%11d ", rating, freq[ rating ] ); if ( freq[ rating ] > largest ) { 88 largest = freq[ rating ]; 89 modevalue = rating; 90 } 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 } 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} void bubblesort( int a[] ) 104{ 105 int pass, j, hold; for ( pass = 1; pass <= SIZE - 1; pass++ ) for ( j = 0; j <= SIZE - 2; j++ ) if ( a[ j ] > a[ j + 1 ] ) { 112 hold = a[ j ]; 113 a[ j ] = a[ j + 1 ]; 114 a[ j + 1 ] = hold; 115 } 116} void printarray( const int a[] ) 119{ 120 int j; for ( j = 0; j <= SIZE - 1; j++ ) { if ( j % 20 == 0 ) 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

28 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 = /ežhµhe H ƒ Õ Ÿ,Õ ******** Median ******** The unsorted array of responses is The sorted array is The median is element 49 of the sorted 99 element array. For this run the median is 7 ******** Mode ******** Response Frequency Histogram /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

29 +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

30 +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 } }; Referencing elements Specify row, then column printf( "%d", b[ 0 ][ 1 ] ); 30

31 1 /* Fig. 6.22: fig06_22.c 2 Double-subscripted array example */ 3 #include <stdio.h> 4 #define STUDENTS 3 5 #define EXAMS 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 ); 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 } }; 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 ) ); 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 ) ); 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 /* Find the minimum grade */ 35 int minimum( const int grades[][ EXAMS ], 36 int pupils, int tests ) 37 { 38 int i, j, lowgrade = 100; 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 ]; return lowgrade; 46 } /* Find the maximum grade */ 49 int maximum( const int grades[][ EXAMS ], 50 int pupils, int tests ) 51 { 52 int i, j, highgrade = 0; 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 ]; return highgrade; 60 } /* 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

32 65 int i, total = 0; for ( i = 0; i <= tests - 1; i++ ) 68 total += setofgrades[ i ]; return ( double ) total / tests; 71 } /* Print the array */ 74 void printarray( const int grades[][ EXAMS ], 75 int pupils, int tests ) 76 { 77 int i, j; printf( " [0] [1] [2] [3]" ); for ( i = 0; i <= pupils - 1; i++ ) { 82 printf( "\nstudentgrades[%d] ", i ); 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] studentgrades[1] studentgrades[2] /ežhµhe H ƒ Õ Ÿ,Õ Lowest grade: 68 Highest grade: 96 The average grade for student 0 is The average grade for student 1 is The average grade for student 2 is

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved. Functions In general, functions are blocks of code that perform a number of pre-defined commands to accomplish something productive. You can either use the built-in library functions or you can create

More information

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays 4 Examples Using Arrays 5 Passing Arrays to Functions 6 Sorting Arrays 7 Case Study: Computing Mean, Median and Mode Using Arrays 8 Searching Arrays

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Lecture 9 Functions Dr M Kasim A Jalil Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson) Objectives In this chapter, you will learn: To understand how to construct programs modularly

More information

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan. Functions Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 5.1 Introduction 5.3 Math Library Functions 5.4 Functions 5.5

More information

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 Arrays Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 6 - Arrays 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays

More information

C: How to Program. Week /Apr/23

C: How to Program. Week /Apr/23 C: How to Program Week 9 2007/Apr/23 1 Review of Chapters 1~5 Chapter 1: Basic Concepts on Computer and Programming Chapter 2: printf and scanf (Relational Operators) keywords Chapter 3: if (if else )

More information

C: How to Program. Week /Apr/16

C: How to Program. Week /Apr/16 C: How to Program Week 8 2006/Apr/16 1 Storage class specifiers 5.11 Storage Classes Storage duration how long an object exists in memory Scope where object can be referenced in program Linkage specifies

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

CSE123. Program Design and Modular Programming Functions 1-1

CSE123. Program Design and Modular Programming Functions 1-1 CSE123 Program Design and Modular Programming Functions 1-1 5.1 Introduction A function in C is a small sub-program performs a particular task, supports the concept of modular programming design techniques.

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

Array. Arrays. Declaring Arrays. Using Arrays

Array. Arrays. Declaring Arrays. Using Arrays Arrays CS215 Peter Lo 2004 1 Array Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name Position number Format: arrayname[ position number] First element

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Arrays. Systems Programming Concepts

Arrays. Systems Programming Concepts Arrays Systems Programming Concepts Arrays Arrays Defining and Initializing Arrays Array Example Subscript Out-of-Range Example Passing Arrays to Functions Call by Reference Multiple-Subscripted Arrays

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4 BIL 104E Introduction to Scientific and Engineering Computing Lecture 4 Introduction Divide and Conquer Construct a program from smaller pieces or components These smaller pieces are called modules Functions

More information

C Functions Pearson Education, Inc. All rights reserved.

C Functions Pearson Education, Inc. All rights reserved. 1 5 C Functions 2 Form ever follows function. Louis Henri Sullivan E pluribus unum. (One composed of many.) Virgil O! call back yesterday, bid time return. William Shakespeare Call me Ishmael. Herman Melville

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved. Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

More information

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

Functions. Systems Programming Concepts

Functions. Systems Programming Concepts Functions Systems Programming Concepts Functions Simple Function Example Function Prototype and Declaration Math Library Functions Function Definition Header Files Random Number Generator Call by Value

More information

BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING)

BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING) 1 BBS 514 YAPISAL PROGRAMLAMA (STRUCTURED PROGRAMMING) 6 LECTURE 7: ARRAYS Lecturer: Burcu Can BBS 514 - Yapısal Programlama (Structured Programming) Arrays (Diziler) Array (Dizi) Group of consecutive

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number

More information

Computer Programming Lecture 14 Arrays (Part 2)

Computer Programming Lecture 14 Arrays (Part 2) Computer Programming Lecture 14 Arrays (Part 2) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr 1 Topics The relationship between

More information

C Functions. Object created and destroyed within its block auto: default for local variables

C Functions. Object created and destroyed within its block auto: default for local variables 1 5 C Functions 5.12 Storage Classes 2 Automatic storage Object created and destroyed within its block auto: default for local variables auto double x, y; Static storage Variables exist for entire program

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 Outline 3.1 Introduction 3.2 Progra m Components in C++ 3.3 Ma th Libra ry Func tions 3.4 Func tions 3.5 Func tion De finitions 3.6 Func tion Prototypes 3.7 He a de r File s 3.8

More information

Chapter 3 - Functions

Chapter 3 - Functions Chapter 3 - Functions 1 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3.4 Functions 3.5 Function Definitions 3.6 Function Prototypes 3.7 Header Files 3.8 Random Number Generation

More information

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++ Chapter 3 - Functions 1 Chapter 3 - Functions 2 3.1 Introduction 3.2 Program Components in C++ 3.3 Math Library Functions 3. Functions 3.5 Function Definitions 3.6 Function Prototypes 3. Header Files 3.8

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Outline Introduction Program Components in C++ Math Library Functions Functions Function Definitions Function Prototypes Header Files Random Number Generation Example: A Game

More information

Content. In this chapter, you will learn:

Content. In this chapter, you will learn: ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual

More information

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa Functions Autumn Semester 2009 Programming and Data Structure 1 Courtsey: University of Pittsburgh-CSD-Khalifa Introduction Function A self-contained program segment that carries out some specific, well-defined

More information

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura CS 2060 Week 4 1 Modularizing Programs Modularizing programs in C Writing custom functions Header files 2 Function Call Stack The function call stack Stack frames 3 Pass-by-value Pass-by-value and pass-by-reference

More information

Programming for Engineers Arrays

Programming for Engineers Arrays Programming for Engineers Arrays ICEN 200 Spring 2018 Prof. Dola Saha 1 Array Ø Arrays are data structures consisting of related data items of the same type. Ø A group of contiguous memory locations that

More information

Multiple-Subscripted Arrays

Multiple-Subscripted Arrays Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and

More information

C Arrays. O b j e c t i v e s In this chapter, you ll:

C Arrays.   O b j e c t i v e s In this chapter, you ll: www.thestudycampus.com C Arrays O b j e c t i v e s In this chapter, you ll: Use the array data structure to represent lists and tables of values. Define an array, initialize an array and refer to individual

More information

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction Functions Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur Programming and Data Structure 1 Function Introduction A self-contained program segment that

More information

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU CSE101-lec#12 Designing Structured Programs Introduction to Functions Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline Designing structured programs in C: Counter-controlled repetition

More information

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR 1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Introduction Function A self-contained program segment that carries

More information

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved. C++ How to Program, 9/e 1992-2014 by Pearson Education, Inc. Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces, or components.

More information

Chapter 5 C Functions

Chapter 5 C Functions Chapter 5 C Functions Objectives of this chapter: To construct programs from small pieces called functions. Common math functions in math.h the C Standard Library. sin( ), cos( ), tan( ), atan( ), sqrt(

More information

Introduction to C Final Review Chapters 1-6 & 13

Introduction to C Final Review Chapters 1-6 & 13 Introduction to C Final Review Chapters 1-6 & 13 Variables (Lecture Notes 2) Identifiers You must always define an identifier for a variable Declare and define variables before they are called in an expression

More information

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming Arrays CSE101-Lec#17 (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU Outline To declare an array To initialize an array To pass an array to a function Arrays Introduction

More information

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single Functions in C++ Problem-Solving Procedure With Modular Design: Program development steps: Analyze the problem Develop a solution Code the solution Test/Debug the program C ++ Function Definition: A module

More information

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays. CS 2060 Week 5 1 Arrays Arrays Initializing arrays 2 Examples of array usage 3 Passing arrays to functions 4 2D arrays 2D arrays 5 Strings Using character arrays to store and manipulate strings 6 Searching

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

6.5 Function Prototypes and Argument Coercion

6.5 Function Prototypes and Argument Coercion 6.5 Function Prototypes and Argument Coercion 32 Function prototype Also called a function declaration Indicates to the compiler: Name of the function Type of data returned by the function Parameters the

More information

CS101 Introduction to computing Function, Scope Rules and Storage class

CS101 Introduction to computing Function, Scope Rules and Storage class CS101 Introduction to computing Function, Scope Rules and Storage class A. Sahu and S. V.Rao Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Outline Functions Modular d l Program Inbuilt

More information

EAS230: Programming for Engineers Lab 1 Fall 2004

EAS230: Programming for Engineers Lab 1 Fall 2004 Lab1: Introduction Visual C++ Objective The objective of this lab is to teach students: To work with the Microsoft Visual C++ 6.0 environment (referred to as VC++). C++ program structure and basic input

More information

Programming for Engineers Functions

Programming for Engineers Functions Programming for Engineers Functions ICEN 200 Spring 2018 Prof. Dola Saha 1 Introduction Real world problems are larger, more complex Top down approach Modularize divide and control Easier to track smaller

More information

Unit 7. Functions. Need of User Defined Functions

Unit 7. Functions. Need of User Defined Functions Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have

More information

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming. Programming Fundamentals for Engineers - 0702113 7. Functions Muntaser Abulafi Yacoub Sabatin Omar Qaraeen 1 Modular programming Your program main() function Calls AnotherFunction1() Returns the results

More information

Programming Assignment #4 Arrays and Pointers

Programming Assignment #4 Arrays and Pointers CS-2301, System Programming for Non-majors, B-term 2013 Project 4 (30 points) Assigned: Tuesday, November 19, 2013 Due: Tuesday, November 26, Noon Abstract Programming Assignment #4 Arrays and Pointers

More information

Fundamentals of Programming Session 13

Fundamentals of Programming Session 13 Fundamentals of Programming Session 13 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2014 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Chapter 7 Array. Array. C++, How to Program

Chapter 7 Array. Array. C++, How to Program Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory

More information

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ FUNCTIONS Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Functions: Program modules in C Function Definitions Function

More information

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions CSE 2421: Systems I Low-Level Programming and Computer Organization Functions Read/Study: Reek Chapters 7 Gojko Babić 01-22-2018 Predefined Functions C comes with libraries of predefined functions E.g.:

More information

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows Unti 4: C Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type An array is used to store a collection of data, but it is often more useful

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Program Components in C++ 2 IS 0020 Program Design and Software Tools Introduction to C++ Programming Lecture 2 Functions and Arrays Jan 13, 200 Modules: functionsand classes Programs use new and prepackaged

More information

ECET 264 C Programming Language with Applications

ECET 264 C Programming Language with Applications ECET 264 C Programming Language with Applications Lecture 10 C Standard Library Functions Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 10

More information

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Function Definitions - Function Prototypes - Data

More information

ONE DIMENSIONAL ARRAYS

ONE DIMENSIONAL ARRAYS LECTURE 14 ONE DIMENSIONAL ARRAYS Array : An array is a fixed sized sequenced collection of related data items of same data type. In its simplest form an array can be used to represent a list of numbers

More information

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University AN OVERVIEW OF C, PART 3 CSE 130: Introduction to Programming in C Stony Brook University FANCIER OUTPUT FORMATTING Recall that you can insert a text field width value into a printf() format specifier:

More information

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch Lecture 3 CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions Review Conditions: if( ) / else switch Loops: for( ) do...while( ) while( )... 1 Examples Display the first 10

More information

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

6-1 (Function). (Function) !*+!#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x (Function) -1.1 Math Library Function!"#! $%&!'(#) preprocessor directive #include !*+!"#!, Function Description Example sqrt(x) square root of x sqrt(900.0) is 30.0 sqrt(9.0) is 3.0 exp(x) log(x)

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. 1992-2010 by Pearson Education, Inc. This chapter serves as an introduction to the important topic of data

More information

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0) Class Teacher: Pralay Mitra Department of Computer Science and Engineering Indian Institute of Technology Kharagpur An Example: Random

More information

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Program Components in C++ 3. Math Library Functions 4. Functions 5. Function Definitions 6. Function Prototypes 7. Header Files 8.

More information

Arrays and Applications

Arrays and Applications Arrays and Applications 60-141: Introduction to Algorithms and Programming II School of Computer Science Term: Summer 2014 Instructor: Dr. Asish Mukhopadhyay What s an array Let a 0, a 1,, a n-1 be a sequence

More information

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type Array Arrays Introduction Group of contiguous memory locations Each memory location has same name Each memory location has same type Remain same size once created Static entries 1 Name of array (Note that

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

Two Dimensional Array - An array with a multiple indexs.

Two Dimensional Array - An array with a multiple indexs. LAB5 : Arrays Objectives: 1. To learn how to use C array as a counter. 2. To learn how to add an element to the array. 3. To learn how to delete an element from the array. 4. To learn how to declare two

More information

C++ Programming Lecture 11 Functions Part I

C++ Programming Lecture 11 Functions Part I C++ Programming Lecture 11 Functions Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Introduction Till now we have learned the basic concepts of C++. All the programs

More information

142

142 Scope Rules Thus, storage duration does not affect the scope of an identifier. The only identifiers with function-prototype scope are those used in the parameter list of a function prototype. As mentioned

More information

Functions and Recursion

Functions and Recursion Functions and Recursion CSE 130: Introduction to Programming in C Stony Brook University Software Reuse Laziness is a virtue among programmers Often, a given task must be performed multiple times Instead

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

Preview from Notesale.co.uk Page 2 of 79

Preview from Notesale.co.uk Page 2 of 79 COMPUTER PROGRAMMING TUTORIAL by tutorialspoint.com Page 2 of 79 tutorialspoint.com i CHAPTER 3 Programming - Environment Though Environment Setup is not an element of any Programming Language, it is the

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) Methods (Deitel chapter 6) 1 Plan 2 Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Methods (Deitel chapter 6)

Methods (Deitel chapter 6) 1 Plan 2 Methods (Deitel chapter ) Introduction Program Modules in Java Math-Class Methods Method Declarations Argument Promotion Java API Packages Random-Number Generation Scope of Declarations Methods

More information

Lab Instructor : Jean Lai

Lab Instructor : Jean Lai Lab Instructor : Jean Lai Group related statements to perform a specific task. Structure the program (No duplicate codes!) Must be declared before used. Can be invoked (called) as any number of times.

More information

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Functions and Recursion

Functions and Recursion Functions and Recursion 1 Storage Classes Scope Rules Functions with Empty Parameter Lists Inline Functions References and Reference Parameters Default Arguments Unary Scope Resolution Operator Function

More information

Two Dimensional Array - An array with a multiple indexs.

Two Dimensional Array - An array with a multiple indexs. LAB5 : Arrays Objectives: 1. To learn how to use C array as a counter. 2. To learn how to add an element to the array. 3. To learn how to delete an element from the array. 4. To learn how to declare two

More information

Lecture 5 C Programming Language

Lecture 5 C Programming Language Lecture 5 C Programming Language Summary of Lecture 5 Pointers Pointers and Arrays Function arguments Dynamic memory allocation Pointers to functions 2D arrays Addresses and Pointers Every object in the

More information

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then 1 7 C Pointers 7.7 sizeof Operator 2 sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then int myarray[ 10 ]; printf( "%d", sizeof(

More information

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop: Matlab? Lecture Slides ME 4060 Machine Vision and Vision-based Control Chapter 3-4 Matlab and IPT Basics By Dr. Debao Zhou 1 MATric LABoratory data analysis, prototype and visualization Matrix operation

More information

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times } Rolling a Six-Sided Die face = 1 + randomnumbers.nextint( 6 ); The argument 6 called the scaling factor represents the number of unique values that nextint should produce (0 5) This is called scaling

More information

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Pointers. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Pointers Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan Outline 7.1 Introduction 7.2 Pointer Variable Definitions and Initialization 7.3 Pointer

More information

Methods: A Deeper Look

Methods: A Deeper Look 1 2 7 Methods: A Deeper Look OBJECTIVES In this chapter you will learn: How static methods and variables are associated with an entire class rather than specific instances of the class. How to use random-number

More information

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers 1 CME 112- Programming Languages II Week 1 Introduction, Scope Rules and Generating Random Numbers Assist. Prof. Dr. Caner Özcan You have two options at any given moment. You can either: Step forward into

More information

Programming for Engineers Iteration

Programming for Engineers Iteration Programming for Engineers Iteration ICEN 200 Spring 2018 Prof. Dola Saha 1 Data type conversions Grade average example,-./0 class average = 23450-67 893/0298 Grade and number of students can be integers

More information