Chapter 4 Functions
Chapter 4 Functions
Chapter 4 Functions
Chapter 4 Functions
4-1 Functions in C
3
1 Overview of functions 2 Definition of function
Engine
wheel
chassis
Division of labor and
cooperation
A B
C D
The form of function definition
Type specifier: used to identify the return value type of a function 。 Eg:
int ,double …
Function name: "see name to know meaning, commonly used to simplify"
Parameter list: a list of various types of variables. The parameters are
separated by commas.
FIGURE 4-3 Structure Chart for a C Program
12
FIGURE 4-4 Function Concept
13
Note
A function in C can have a return value,
a side effect, or both.
14
PROGRAMSample
4-1 Program with Subfunction
15
PROGRAMSample
4-1 Program with Subfunction
16
PROGRAMSample
4-1 Program with Subfunction
17
User-Defined Functions
Like every other object in C, functions
must be both declared and defined. The
function declaration gives the whole
picture of the function that needs to be
defined later. The function definition
contains the code for a function.
Topics discussed in this section:
Basic Function Designs
Function Definition
Function Declaration
The Function Call
18
Chapter 4 Fuctions
4.2 Basics of Function
20
PROGRAMvoid
4-2 Function with a Parameter
21
PROGRAMvoid
4-2 Function with a Parameter
22
FIGURE 4-7 Non-void Function without Parameters
23
FIGURE 4-8 Calling a Function That Returns a Value
24
PROGRAM 4-3
Read a Number and Square It
25
PROGRAM 4-3
Read a Number and Square It
26
PROGRAM 4-3
Read a Number and Square It
27
PROGRAM 4-3
Read a Number and Square It
28
Chapter 4 Fuctions
4.3 Function Call
#include<stdio.h>
main()
{
float add(float x, float y); /* prototype
(declaration of add) */
float a, b, c;
scanf("%f,%f", &a, &b);
c = add(a, b);
printf("sum is %f\n", c);
}
float add(float x, float y) /*definition of add*/
{
float z;
z = x + y;
return(z);
}
Chapter 4 Fuctions
4.3 Function Call
34
FIGURE 4-12 Parts of a Function Call
35
FIGURE 4-13 Examples of Function Calls
36
PROGRAM 4-4
Print Least Significant Digit
37
PROGRAM 4-4
Print Least Significant Digit
38
PROGRAM 4-4
Print Least Significant Digit
39
Chapter 4 Fuctions
4.4 Parameters and Returning Value of Function
Example:
#include <stdio.h>
void swap(int x, int y); void swap(int x, int y)
main() {
{ int t;
int a=10, b=200; t=x;
swap(a,b); x=y;
printf(“a=%d\tb=%d\n", a,b); y=t;
} }
45
PROGRAM 4-5
Add Two Digits
46
PROGRAM 4-5
Add Two Digits
47
PROGRAM 4-5
Add Two Digits
48
Exercises
P.71 4-1
P.88 4-13