Functions in C Math Library Functions Function Definitions
Functions in C Math Library Functions Function Definitions Function Prototypes Header Files Calling Functions: Call by Value and Call by Reference Random Number Generation Example: A Game of Chance
Math Library Functions • Math library functions – perform common mathematical calculations – #include <math. h> • Format for calling functions Function. Name (argument); • If multiple arguments, use comma-separated list – printf( "%. 2 f", 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
Math Library Functions • double acos(double x) -- Compute arc cosine of x. double asin(double x) -- Compute arc sine of x. double atan(double x) -- Compute arc tangent of x. double atan 2(double y, double x) -- Compute arc tangent of y/x. double ceil(double x) -- Get smallest integral value that exceeds x. double cos(double x) -- Compute cosine of angle in radians. double cosh(double x) -- Compute the hyperbolic cosine of x. div_t div(int number, int denom) -- Divide one integer by another. double exp(double x -- Compute exponential of x double fabs (double x ) -- Compute absolute value of x. double floor(double x) -- Get largest integral value less than x. double fmod(double x, double y) -- Divide x by y with integral quotient and return remainder. double frexp(double x, int *expptr) -- Breaks down x into mantissa and exponent of no. labs(long n) -- Find absolute value of long integer n. double ldexp(double x, int exp) -- Reconstructs x out of mantissa and exponent of two. ldiv_t ldiv(long number, long denom) -- Divide one long integer by another. double log(double x) -- Compute log(x). double log 10 (double x ) -- Compute log to the base 10 of x. double modf(double x, double *intptr) -- Breaks x into fractional and integer parts. double pow (double x, double y) -- Compute x raised to the power y. double sin(double x) -- Compute sine of angle in radians. double sinh(double x) - Compute the hyperbolic sine of x. double sqrt(double x) -- Compute the square root of x. void srand(unsigned seed) -- Set a new seed for the random number generator (rand). double tan(double x) -- Compute tangent of angle in radians. double tanh(double x) -- Compute the hyperbolic tangent of x. http: //www. cs. cf. ac. uk/Dave/C/node 17. html#SECTION 0017100000000
Function Definitions • 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)
• 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 /* Finding the maximum of three integers */ #include <stdio. h> int maximum( int, int ); /* function prototype */ int main() { int a, b, c; printf( "Enter three integers: " ); scanf( "%d%d%d", &a, &b, &c ); printf( "Maximum is: %dn", maximum( a, b, c ) ); return 0; } 1. Function prototype (3 parameters) 2. Input values 2. 1 Call function 3. Function definition /* Function maximum definition */ int maximum( int x, int y, int z ) { int max = x; if ( y > max ) max = y; if ( z > max ) max = z; return max; } Enter three integers: 22 85 17 Maximum is: 85 Program Output
Function Prototypes • 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 ); • Takes in 3 ints • Returns an int • Promotion rules and conversions – Converting to lower types can lead to errors
Header Files • 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
Calling Functions: Call by Value and Call by Reference • 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
Random Number Generation • 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 for every function call • 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
Random Number Generation (II) • 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 /* 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 1. Initialize seed 2. Input value for seed 2. 1 Use srand to change random sequence 11 printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 2. 2 Define Loop 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { 16 printf( "%10 d", 1 + ( rand() % 6 ) ); 17 18 if ( i % 5 == 0 ) 19 printf( "n" ); 20 } 21 22 return 0; 23 } 3. Generate and output random numbers
Enter seed: 67 6 1 4 6 2 1 6 4 Enter seed: 867 2 4 6 1 1 3 6 2 Enter seed: 67 6 1 4 6 2 1 6 4 Program Output
Example: A Game of Chance • 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 /* Craps */ #include <stdio. h> #include <stdlib. h> #include <time. h> int roll. Dice( void ); int main() { int game. Status, sum, my. Point; srand( time( NULL ) ); sum = roll. Dice(); /* first roll of the dice */ switch ( sum ) { case 7: case 11: /* win on first roll */ game. Status = 1; break; case 2: case 3: case 12: /* lose on first roll */ game. Status = 2; break; default: /* remember point */ game. Status = 0; my. Point = sum; printf( "Point is %dn", my. Point ); break; } while ( game. Status == 0 ) { /* keep rolling */ sum = roll. Dice(); 1. roll. Dice prototype 1. 1 Initialize variables 1. 2 Seed srand 2. Define switch statement for win/loss/continue 2. 1 Loop
33 if ( sum == my. Point ) /* win by making point */ 34 game. Status = 1; 35 else 36 if ( sum == 7 ) /* lose by rolling 7 */ 37 game. Status = 2; 38 } 39 2. 2 Print win/loss 40 if ( game. Status == 1 ) 41 printf( "Player winsn" ); 42 else 43 printf( "Player losesn" ); 44 45 return 0; 46 } 47 48 int roll. Dice( void ) 49 { 50 int die 1, die 2, work. Sum; 51 52 die 1 = 1 + ( rand() % 6 ); 53 die 2 = 1 + ( rand() % 6 ); 54 work. Sum = die 1 + die 2; 55 printf( "Player rolled %d + %d = %dn", die 1, die 2, work. Sum ); 56 return work. Sum; 57 } Player rolled 6 + 5 = 11 Player wins Program Output
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 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 Program Output
- Slides: 17