Functions: 2000 Prentice Hall, Inc. All Rights Reserved
Functions: 2000 Prentice Hall, Inc. All Rights Reserved
5.1
Introduction
5.2
Program Modules in C
Functions
Modules in C
Programs combine user-defined functions with library functions
C standard library has a wide variety of functions
Function calls
Invoking functions
Provide function name and arguments (data)
Function performs operations or manipulations
Function returns results
Function call analogy:
Boss asks worker to complete task
5.3
5.4
Functions
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 of functions
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new programs
Abstraction - hide internal details (library functions)
Examining printMessage
#include <stdio.h>
void printMessage ( void ) ;
int main ( void )
{
printMessage ( ) ;
return 0 ;
}
function prototype
function call
function
body
function definition
printMessage (void) ;
no arguments
Possibilities
A function may:
5.5
Function Definitions
5.5
Function Definitions
Returning control
If nothing returned
return;
or, until reaches right brace
If something returned
return expression;
Outline
3#include <stdio.h>
4
5int maximum( int, int, int );
/* function prototype */
6
7int main()
1. Function prototype
(3 parameters)
8{
9
int a, b, c;
10
11
12
13
14
15
return 0;
2. Input values
2.1 Call function
3. Function definition
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 }
5.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
The function with the prototype
int maximum( int, int, int );
Takes in 3 ints
Returns an int
Header Files
Header files contain function prototypes for all of
the functions found in the specified library.
They also contain definitions of constants and data
types used in that library.
5.8
Call by reference
Passes original argument
Changes in function effect original
Only used with trusted functions
5.13 Recursion
Recursive functions
Functions that call themselves
Can only solve a base case
Divide a problem up into
What it can do
What it cannot do
What it cannot do resembles original problem
The function launches a new copy of itself (recursion
step) to solve what it cannot do
5.13 Recursion
Example: factorials
5! = 5 * 4 * 3 * 2 * 1
Notice that
5! = 5 * 4!
4! = 4 * 3! ...
#include <stdio.h>
int fact(int);
void main()
{
int number,f;
scanf(%d,&number);
f=fact(number);
printf(%d,f);
}
return
return
f( 1 )
return 1
f( 2 )
f( 0 )
f( 1 )
return 1
return 0
Outline
3#include <stdio.h>
4
5long fibonacci( long );
1. Function prototype
6
7int main()
8{
9
10
11
12
13
14
15
return 0;
17
18 /* Recursive definition of function fibonacci */
19 long fibonacci( long n )
20 {
22
23
24
2. Input an integer
2.1 Call function
fibonacci
2.2 Output results.
16 }
21
3. Define fibonacci
recursively
if ( n == 0 || n == 1 )
return n;
else
return fibonacci( n - 1 ) + fibonacci( n - 2 );
25 }
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
Program Output
Enter an integer: 2
Fibonacci(2) = 1
Enter an integer: 3
Fibonacci(3) = 2
Outline
Program Output
Enter an integer: 4
Fibonacci(4) = 3
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
Termination
Iteration: loop condition fails
Recursion: base case recognized
5.7
Header Files
Header files
Contain function prototypes for library functions
<stdlib.h> , <math.h> , etc
Load with #include <filename>
#include <math.h>
5.9
srand function
<stdlib.h>
Takes an integer seed and jumps to that location in its
"random" sequence
srand( seed );
//load <time.h>
time( NULL )
Returns the time at which the program was compiled in
seconds
Randomizes" the seed
Outline
#include <stdlib.h>
#include <stdio.h>
1. Initialize seed
int main()
int i;
unsigned seed;
10
11
12
13
srand( seed );
14
15
16
17
18
if ( i % 5 == 0 )
19
20
printf( "\n" );
}
21
22
23 }
return 0;
Enter seed: 67
6
1
1
6
4
1
6
6
2
4
4
1
6
3
1
6
6
2
Enter seed: 67
6
1
1
6
4
1
6
6
2
4
Outline
Program Output
Outline
Craps */
3#include <stdio.h>
4#include <stdlib.h>
1. rollDice
prototype
5#include <time.h>
6
7int rollDice( void );
8
9int main()
10 {
11
12
13
14
sum = rollDice();
15
16
switch ( sum ) {
17
18
gameStatus = 1;
19
break;
20
21
gameStatus = 2;
22
break;
23
default:
2.1 Loop
/* lose on first roll */
/* remember point */
24
gameStatus = 0;
25
myPoint = sum;
26
27
break;
28
2. Define switch
statement for
win/loss/continue
29
30
31
32
while ( gameStatus == 0 ) {
sum = rollDice();
/* keep rolling */
33
if ( sum == myPoint )
34
gameStatus = 1;
35
Outline
else
36
if ( sum == 7 )
37
38
/* lose by rolling 7 */
gameStatus = 2;
39
40
41
42
43
if ( gameStatus == 1 )
printf( "Player wins\n" );
else
printf( "Player loses\n" );
44
45
return 0;
46 }
47
48 int rollDice( void )
49 {
50
51
52
die1 = 1 + ( rand() % 6 );
53
die2 = 1 + ( rand() % 6 );
54
55
56
57 }
Player rolled 6 + 5 = 11
Player wins
Program Output
Player rolled 6 + 6 = 12
Player loses
Player rolled
Point is 10
Player rolled
Player rolled
Player rolled
Player rolled
Player wins
4 + 6 = 10
Player rolled
Point is 4
Player rolled
Player rolled
Player rolled
Player rolled
Player rolled
Player rolled
Player loses
1 + 3 = 4
2
6
3
6
1
5
4
6
1
5
+
+
+
+
+
+
+
+
+
+
4
5
3
4
4
4
6
3
2
2
=
=
=
=
=
=
=
=
=
=
6
11
6
10
Outline
Program Output
5
9
10
9
3
7
Automatic storage
Object created and destroyed within its block
auto: default for local variables
auto double x, y;
Function scope
Can only be referenced inside a function body
Used only for labels (start:, case: , etc.)
Outline
A scoping example */
3#include <stdio.h>
4
5void a( void );
/* function prototype */
6void b( void );
/* function prototype */
7void c( void );
/* function prototype */
8
9int x = 1;
/* global variable */
1. Function prototypes
1.1 Initialize global
variable
10
11 int main()
12 {
13
int x = 5;
14
15
16
17
18
2. Call functions
19
21
22
23
20
3. Output results
24
25
a();
26
b();
27
c();
/* c uses global x */
28
a();
29
b();
30
c();
31
32
33
return 0;
34 }
Outline
3.1 Function definitions
35
36 void a( void )
37 {
38
int x = 25;
39
40
41
++x;
42
43 }
44
45 void b( void )
46 {
47
48
49
50
++x;
51
52 }
53
54 void c( void )
55 {
56
57
x *= 10;
58
59 }
Outline
Program Output
5.13 Recursion
Recursive functions
Functions that call themselves
Can only solve a base case
Divide a problem up into
What it can do
What it cannot do
What it cannot do resembles original problem
The function launches a new copy of itself (recursion
step) to solve what it cannot do
5.9
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