CHTP5e 05-Functions 1
CHTP5e 05-Functions 1
5
C Functions
2
OBJECTIVES
In this chapter you will learn:
To construct programs modularly from small pieces
called functions.
The common math functions available in the C
Standard Library.
To create new functions.
The mechanisms used to pass information between
functions.
Simulation techniques using random number
generation.
How to write and use recursive functions, i.e., functions
that call themselves.
3
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 Function Call Stack and Activation Records
5.8 Headers
5.9 Calling Functions: Call-by-Value and Call-by-
Reference
4
5.1 Introduction
Divide and conquer
– Construct a program from smaller pieces or components
- These smaller pieces are called modules
– Each piece more manageable than the original program
6
Error-Prevention Tip
5.4 Functions
Functions
– Modularize a program
– All variables defined 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)
– Avoid code repetition
13
1 4 9 16 25 36 49 64 81 100
18
unsigned int %u %u
int %d %d
unsigned short %hu %hu
short %hd %hd
char %c %c
5.8 Headers
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
33
<assert.h> Contains macros and information for adding diagnostics that aid
program debugging.
<ctype.h> Contains function prototypes for functions that test characters for
certain properties, and function prototypes for functions that can
be used to convert lowercase letters to uppercase letters and vice
versa.
<errno.h> Defines macros that are useful for reporting error conditions.
<float.h> Contains the floating-point size limits of the system.
<limits.h> Contains the integral size limits of the system.
<locale.h> Contains function prototypes and other information that enables a
program to be modified for the current locale on which it is
running. The notion of locale enables the computer system to
handle different conventions for expressing data like dates, times,
dollar amounts and large numbers throughout the world.
Face Frequency
1 1003
2 1017
3 983
4 994
5 1004
6 999
42
Enter seed: 67
6 1 4 6 2
1 6 1 6 4
Enter seed: 67
6 1 4 6 2
1 6 1 6 4