Functions in C Outline 1 Introduction 2 Program Modules in C 3 Math Library Functions 4 Functions 5 Function Definitions 6 Function Prototypes 7 Header Files 8 Calling Functions: Call by Value and Call by Reference 9 Random Number Generation 10 Example: A Game of Chance 11 Storage Classes 12 Scope Rules 13 Recursion 14 Example Using Recursion: The Fibonacci Series 15 Recursion vs. Iteration
Functions in C. Outline 1Introduction 2Program Modules in C 3Math Library Functions 4Functions 5Function Definitions 6Function Prototypes 7Header Files 8Calling Functions: Call by Value and Call by Reference 9Random Number Generation 10Example: A Game of Chance - PowerPoint PPT Presentation
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Functions in C
Outline1 Introduction2 Program Modules in C3 Math Library Functions4 Functions5 Function Definitions6 Function Prototypes7 Header Files8 Calling Functions: Call by Value and Call by
Reference9 Random Number Generation10 Example: A Game of Chance11 Storage Classes12 Scope Rules13 Recursion14 Example Using Recursion: The Fibonacci Series15 Recursion vs. Iteration
1 Introduction
• Divide and conquer – Construct a program from smaller pieces or
components
– Each piece more manageable than the original program
2 Program Modules in C
• Functions– 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
2 Program Modules in C (II)
• 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
3 Math Library Functions
• Math library functions – perform common mathematical calculations– #include <math.h>
• Format for calling functionsFunctionName (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
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 atan2(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 log10 (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.
• 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. Function prototype (3 parameters)
2. Input values
2.1 Call function
3.Function definition
Program Output
1 /*2 Finding the maximum of three integers */3 #include <stdio.h>45 int maximum( int, int, int ); /* function prototype */67 int main()8 {9 int a, b, c;1011 printf( "Enter three integers: " );12 scanf( "%d%d%d", &a, &b, &c );13 printf( "Maximum is: %d\n", maximum( a, b, c ) );1415 return 0;16 }1718 /* Function maximum definition */19 int maximum( int x, int y, int z )20 {21 int max = x;2223 if ( y > max )24 max = y;2526 if ( z > max )27 max = z;2829 return max;30 }
Enter three integers: 22 85 17Maximum is: 85
6 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, int );• Takes in 3 ints
• Returns an int
• Promotion rules and conversions– Converting to lower types can lead to errors
7 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
8 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
9 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
9 Random Number Generation (II)
• srand function– <stdlib.h>– Takes an integer seed - jumps to location in "random" sequence
– Player must roll his point before rolling 7 to win
1. rollDice prototype
1.1 Initialize variables
1.2 Seed srand
2. Define switch statement for win/loss/continue
2.1 Loop
1 /*2 Craps */3 #include <stdio.h>4 #include <stdlib.h>5 #include <time.h>67 int rollDice( void );89 int main()10 {11 int gameStatus, sum, myPoint;1213 srand( time( NULL ) );14 sum = rollDice(); /* first roll of the dice */1516 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 }2930 while ( gameStatus == 0 ) { /* keep rolling */31 sum = rollDice();32
2.2 Print win/loss
Program Output
33 if ( sum == myPoint ) /* win by making point */