2.functions Updated
2.functions Updated
1-2
Introduction
1-3
Hierarchical boss function/worker function relationship
OBJECTIVES
To construct programs modularly from small pieces called
functions.
The common math functions available in the C Standard
Library.
How to create new functions.
The mechanisms used to pass information between functions.
How to write and use recursive functions, i.e., functions that
call themselves.
Predefined Functions
In C, a function is similar to that of a function in algebra
It has a name
Ex:
Calls function sqrt, which returns the square root of its argument
Predefined Functions (cont'd.)
Function sqrt as a “Black Box”
Predefined Functions (cont'd.)
Ex: If w is 9.0, the assignment statement
z = 5.7 + sqrt(w);
is evaluated as follows:
1. w is 9.0, so function sqrt computes the
square root of 9.0, or 3.0.
2. The values 5.7 and 3.0 are added together.
3. The sum, 8.7, is stored in z.
function
Arguments may be constants, variables, or expressions
Commonly used math library functions
Function Description Example
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
i = rand();
Pseudorandom
Preset sequence of "random" numbers
Scaling
To get a random number between 1 and n
1 + ( rand() % n ) // 0 n-1
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
General rule: low + rand()%(high-low+1)
Random from 5 to 100 is: 5 + rand()%(100-5+1)
OBJECTIVES
To construct programs modularly from small pieces called
functions.
The common math functions available in the C Standard
Library.
How to create new functions.
The mechanisms used to pass information between functions.
How to write and use recursive functions, i.e., functions that
call themselves.
Tips
• In programs containing many functions, main is
often implemented as a group of calls to functions
that perform the bulk of the program’s work.
Removed from the memory after the function completed its task
Parameters
Communicate information between functions
1 4 9 16 25 36 49 64 81 100
Function Prototypes
Function prototype
Function name
in program
The function with the prototype
unsigned int %u %u
int %d %d
Low
unsigned short %hu %hu
short %hd %hd
char %c %c
OBJECTIVES
To construct programs modularly from small pieces called
functions.
The common math functions available in the C Standard
Library.
How to create new functions.
The mechanisms used to pass information between functions.
How to write and use recursive functions, i.e., functions that
call themselves.
Calling Functions: Call by Value and Call by Reference
Call by value
Copy of argument passed to function
Call by reference
Passes original argument
local x in main is 5
OBJECTIVES
To construct programs modularly from small pieces called
functions.
The common math functions available in the C Standard
Library.
How to create new functions.
The mechanisms used to pass information between functions.
Review