CO1003 Chapter 6 Functions
CO1003 Chapter 6 Functions
Chapter 6: Functions
3
Content
Introduction
Summary
4
Introduction
In the previous chapters, we have used
several so-called functions in the library:
◼ printf in stdio.h
Those functions are modular
◼ scanf in stdio.h
processing units that are:
◼ fflush in stdio.h
→Responsible for a
◼ sqrt in math.h
certain task
◼ pow in math.h
◼ system in stdlib.h →Reusable in many
◼ strcpy in string.h
5
Functions in the standard library
Source: www.tutorialspoint.com 6
Functions in the standard library
Some functions in <stdio.h>
◼ int printf(const char *format, ...)
Sends formatted output to stdout
Repeated code!!!
Can we just code
them once and then
make use of them
over the time just
like those in the
standard library? 10
Introductions
Let’s define a function: getNaturalNumber()
Compile:
gcc C6_starTriangle_function_1.c C6_function_getNaturalNumber.c
–o C6_starTriangle_function_1.exe 12
Introduction
A function
◼ A processing unit to perform a specific task
◼ A means to modularize a program for
manageable program development
C Program 1 C Program 2
main() main()
Divide-and-conquer
◼ Function definition
◼ Function declaration
◼ Function call
14
An example of a function
Prepare your own library for numbers
◼ Compute the sum of N first natural numbers
sum = 1 + 2 + 3 + … + (N-1) + N
◼ Compute the factorial of N, a natural number
factorial = 1*2*3*…*(N-1)*N
◼ Compute the n-th power of x, a floating-point
number
xn = x*x*x*…*x
◼ Count the number of digits in N, a natural number
N = 123456 => Number of digits = 6
◼ Round x, a floating-point number, with two digits
after the decimal point
x = 1.23456 => x = 1.23
x = 9.87654321 => x = 9.88 15
An example of a function
Prepare your own library for numbers
◼ Check if a natural number is a prime number
7 => true ( 0)
8 => false (0)
◼ Check if a natural number is a squared number
4 => true ( 0)
8 => false (0)
◼ Toggle non-zero digits to ‘9’ digits in an integer number to
generate its 9-based mask
113789 => 999999
-10789 => -90999
◼ Count the number of occurrences of each digit in an integer
number
113789 => 0: 0; 1: 2; 2: 0; 3: 1; 4: 0; 5: 0; 6: 0; 7: 1; 8: 1; 9: 1
-20054 => 0: 2; 1: 1; 2: 1; 3: 0; 4: 1; 5: 1; 6: 0; 7: 0; 8: 0; 9: 0
An example of a function
Prepare your own library for numbers
◼ Estimate a value of e, the natural number
◼ Estimate a value of ex
◼ Estimate a value of PI
◼ … 17
Components of a function
Given N, a natural number, calculate the
factorial of N: N! = 1*2*..*N = (N-1)!*N
18
Components of a function
Given N, a natural number, calculate the
factorial of N: N! = 1*2*..*N = (N-1)!*N
19
Components of a function
[static] return-type function-name (argument-declarations)
{
declarations and statements
}
- function-name: a valid identifier
- argument-declarations: a list of formal parameters in communication
Part
+ Each parameter is regarded as a local variable with a data type.
of the + Each parameter can be specified with “const” for unchanged intention.
input
+ Each parameter can be passed by value or by reference if it is a pointer.
Process - declarations: a list of local variables
ing in + Each variable can be auto or static with one single initialization.
its
body - statements: zero, one, or many statements of any kind
- return-type: a valid data type or void
Part + Statement return [<expression>]; in the body is used to end the
of the
output called function and return [a value] to its caller. If not, close brace of the
body ends the called function and program control is switched to its caller.
- [static]: optional specification to make the function available only in the file
Charac
teristic where it is defined. 20
Concepts related to functions
Function definition:
[static] return-type function-name (argument-declarations)
{
declarations and statements
}
Function prototype:
return-type function-name (argument-declarations);
Function signature:
[extern] return-type function-name (argument-declarations)
Function definition
= Function declaration
(as it is placed before its call)
Function declaration
a call to a function
Function definition
(a function declaration is required
as it is placed after its call.) 23
Where is a function defined and
declared?
SEPARATED FILES
Function declaration
Function
definition
Function calls
24
Where is a function defined and
declared?
Source file
getFactorial.c
25
Where is a function defined and
declared?
Source file
getPower.c
26
Where is a function defined and
declared?
Header file for common use
mynumber.h
27
Function call
Function call is a mention of a function to
another function or itself.
◼ The function whose function body contains a a
mention is called a calling function or a caller.
◼ The function whose name is mentioned in the caller’s
function body is called a called function or a callee.
◼ The caller is the same as or different from the callee.
The program in C6_function_myNumber
◼ The main() function calls the printf(), scanf(), pow(),
factorial(), and power() functions.
Caller = main
Callees = printf, scanf, pow, factorial, power 28
Function call
A function call is mentioned in the function
body of the caller as:
function-name (argument-list)
◼ argument-list
Optional, i.e. empty if the callee has no argument
Each argument is called actual parameter which is an
expression corresponding to a formal parameter by order.
Each argument has a type compatible with the type of its
corresponding formal parameter. Otherwise, type
conversion with promotion or truncation is performed.
Assignment of each expression value to the
corresponding formal parameter’s memory is performed.
◼ A value of a return type (if it is not void) is
returned via this function call. 29
Stack’s values when i=0 in the
0 i 2 x
10 n 0 n
2 x i
0 e_x aPower
The caller
30
The callee
Function call
Function call by value
◼ Parameters are passed by value.
The actual parameter values are copied into local storage
of the formal parameters of the callee.
◼ The caller and callee do not share any memory.
Function call by reference
◼ C has no explicit reference parameters but
implements them via pointers, i.e. address passing.
◼ Pointers are passed to the arguments.
There is only one copy of the value at any time.
◼ The caller and callee have access to the value in
their shared memory through pointers. 31
Function call
A function to swap two integer numbers
void swap(int a, int b){
int temp;
a and b will be passed by
temp = a; values of int type.
a = b;
b = temp;
}
void swap(int *a, int *b){
int temp;
temp = *a; a and b will be passed by pointers
*a = *b; to int values, i.e. addresses of the
memory that contains int values.
*b = temp;
}
32
Function call by value
10 a 10 a
9 b 9 b
temp
Stack’s values
before the callee
ends
Callee’s stack
9 a
10 b
10 temp
34
Function call by reference
Stack’s values
before the callee
ends
Caller’s stack Callee’s stack
000000000022FE4C
9 a &a 000000000022FE4C a
000000000022FE48 &b
10 b
000000000022FE48
b
10 temp
36
Recursion
A recursive function is a function that calls
itself either directly or indirectly.
When a function calls itself recursively, each
invocation gets a fresh set of all the automatic
variables, independent of the previous set.
9*rFactorial(8) 9* 8*7*6*5*4*3*2*1*1
8*rFactorial(7) 8*7*6*5*4*3*2*1*1
7*rFactorial(6) 7*6*5*4*3*2*1*1
6*rFactorial(5) 6*5*4*3*2*1*1
5*rFactorial(4) 5*4*3*2*1*1
4*rFactorial(3) 4*3*2*1*1
3*rFactorial(2) 3*2*1*1
2*rFactorial(1) 2*1*1
Recursive cases
with smaller sizes 1*rFactorial(0) 1*1
Return path
Base case 1 1 38
Recursion
Writing a recursive function
◼ Determine and write the base cases and their
solutions
No recursive call is specified for those base cases.
41
Recursion
Estimate a value of ex
◼ Recursive case:
42
Recursion
Estimate a value of PI
◼ Recursive case:
43
Recursion
Hanoi Tower
Move disks from peg 1 to
peg 3 using peg 2 as a
temporary holding area in
such a way that smaller
disks are always on top of
larger disks and one disk peg 1 peg 2 peg 3
is moved at a time
45
Hanoi Tower
◼ Reusability
◼ Information hiding
◼ Abstraction
Function declaration
Function call
◼ By value
Recursion
◼ Recursive problem
50