Chapter 5 - Functions: 2000 Prentice Hall, Inc. All Rights Reserved
Chapter 5 - Functions: 2000 Prentice Hall, Inc. All Rights Reserved
Outline
5.1
Introduction
5.2
Program Modules in C
5.3
Math Library Functions
5.4
Functions
5.5
Function Definitions
5.6
Function Prototypes
5.7
Header Files
5.8
Calling Functions: Call by Value and Call by
Reference
5.9
Random Number Generation
5.10
Example: A Game of Chance
5.11
Storage Classes
5.12
Scope Rules
5.13
Recursion
5.14
Example Using Recursion: The Fibonacci Series
5.15
Recursion vs. Iteration
2000 Prentice Hall, Inc. All rights reserved.
5.1
Introduction
5.2
Program Modules in C
Functions
Modules in C
Programs written by combining user-defined functions with
library functions
5.2
Function calls
Invoking functions
Provide function name and arguments (data)
Function performs operations or manipulations
Function returns results
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
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new programs
Abstraction - hide internal details (library functions)
5.5
Function Definitions
Functiondefinitionformat
returnvaluetypefunctionname( parameterlist )
{
declarationsandstatements
}
5.5
Functiondefinitionformat(continued)
returnvaluetypefunctionname( parameterlist )
{
declarationsandstatements
}
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
/* function prototype */
int main()
{
int a, b, c;
printf( "Enter three integers: " );
scanf( "%d%d%d", &a, &b, &c );
printf( "Maximum is: %d\n", maximum( a, b, c ) );
return 0;
}
/* 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;
}
Outline
1. Function prototype
(3 parameters)
2. Input values
2.1 Call function
3. Function definition
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
int maximum( int, int, int );
Takes in 3 ints
Returns an int
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.8
Call by reference
Passes original argument
Changes in function effect original
Only used with trusted functions
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 )
5.9
srand function
<stdlib.h>
Takes an integer seed - jumps to location in "random" sequence
srand( seed );
srand( time( NULL ) ); //load <time.h>
#include <stdlib.h>
#include <stdio.h>
5
6
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
return 0;
Outline
1. Initialize seed
2. Input value for seed
2.1 Use srand to
change random
sequence
2.2 Define Loop
3. Generate and
output random
numbers
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
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
Outline
1. rollDice
prototype
switch ( sum ) {
case 7: case 11:
/* win on first roll */
gameStatus = 1;
break;
case 2: case 3: case 12: /* lose on first roll */
gameStatus = 2;
break;
default:
/* remember point */
gameStatus = 0;
myPoint = sum;
printf( "Point is %d\n", myPoint );
break;
}
while ( gameStatus == 0 ) {
sum = rollDice();
2000 Prentice Hall, Inc. All rights reserved.
/* keep rolling */
2. Define switch
statement for
win/loss/continue
2.1 Loop
33
if ( sum == myPoint )
34
gameStatus = 1;
35
if ( sum == 7 )
37
/* lose by rolling 7 */
gameStatus = 2;
39
40
41
42
43
Outline
else
36
38
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
return workSum;
57 }
Player rolled 6 + 5 = 11
Player wins
2000 Prentice Hall, Inc. All rights reserved.
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
5
9
10
9
3
7
Outline
Program Output
Automatic storage
Object created and destroyed within its block
auto: default for local variables
auto double x, y;
register: triestoputvariableintohighspeedregisters
Canonlybeusedforautomaticvariables
register int counter = 1;
Function scope
1
2
3
4
5
6
7
void a( void );
void b( void );
void c( void );
/* function prototype */
/* function prototype */
/* function prototype */
8
9 int x = 1;
10
11 int main()
12 {
13
14
15
16
17
18
19
20
int x = 5;
1. Function prototypes
1.1 Initialize global
variable
1.2 Initialize local
variable
1.3 Initialize local
variable in block
2. Call functions
21
22
23
24
25
26
27
28
a();
b();
c();
a();
29
30
/* global variable */
Outline
a
b
c
a
b();
/* static local x retains its previous value */
2000
Prentice Hall, Inc.
rights reserved.
c();
/* All
global
x also retains its value */
3. Output results
31
32
33
return 0;
Outline
34 }
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
Outline
Program Output
5.13 Recursion
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)
Gets plugged in, works its way up and solves whole problem
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;
long fibonacci(long n)
{
if (n==0 || n==1) //base case
return n;
else return fibonacci(n-1) + fibonacci(n-2);
}
return
return
f( 1 )
return 1
f( 2 )
f( 0 )
return 0
f( 1 )
return 1
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
Enter an integer: 0
Fibonacci(0) = 0
Enter an integer: 1
Fibonacci(1) = 1
2000 Prentice Hall, Inc. All rights reserved.
Outline
1. Function prototype
1.1 Initialize variables
2. Input an integer
2.1 Call function
fibonacci
2.2 Output results.
3. Define fibonacci
recursively
Program Output
Enter an integer: 2
Fibonacci(2) = 1
Outline
Enter an integer: 3
Fibonacci(3) = 2
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
Program Output
Termination
Iteration: loop condition fails
Recursion: base case recognized