4 ModularProgramming
4 ModularProgramming
Basics of C Language
Part IV: Modular Programming
Modularization
Systematic approach to
programming
5 University of Oulu
Modular Example
programming
*
Matchstick man, figure to be drawn * *
* *
A circle / \
/ \
A baseline / \
_____________
Lines
/ \
/ \
/ \
6 University of Oulu
Modular programming
Analysis: Top-down
The figure includes the elements circle, ”triangle” (i.e. lines and the
baseline) and a ”triangle without the baseline” (i.e., lines)
1. Draw a circle
2. Draw a triangle
3. Draw lines
7 University of Oulu
Modular programming
Analysis: Structural graph
Draw a
matchstick man
Level 1
8 University of Oulu
Modular programming
Sructural graph
• Defines the original problem, step-by-step, from the top, rough
level description to the lowest, most precise level.
• The structural graph presents the interdependencies of the
sub-problems and the order of the execution
• We want to follow the similar kind of approach not only in the
design but also in the implementation of the solution, thus…
• We will utilize the concept of a function.
9 University of Oulu
FUNCTIONS in
C
University of Oulu
Functions A function
• A function combines statements
into one program unit, a module.
• The idea of modularization is to
increase understandability,
testability and maintainability
• A function is intended to perform a
single, accurately defined task
• Library functions, such as printf
and scanf
• Functions defined by the
programmer (= someone like you)
University of Oulu
Functions
A function is activated by a function call, which is a common
executable statement in C, e.g..
myFunction();
12 University of Oulu
Functions
#include <stdio.h>
2
int main(void) { void myFunction(void) {
3
… …
statement1; 1
statement4;
statement2;
statement3; statement5;
myFunction(); return 0;
statementN; }
… 5 4
return 0;
}
13 University of Oulu
Functions
Example
A main function for a program
that draws a matchstick man.
The ”drawing” functionality is
Functions implemented in three separate
functions.
14 University of Oulu
Benefits from utilizing functions
Abstraction, i.e., postponing the decisions Design & implement the main algorithm
for the details and implementing a program Design lower level algorithm(s) & implement
in smaller, manageable pieces. required function(s), as needed
Fewer lines of code - therefore possibly less errors, too! Easier to test, too!
University of Oulu
Function parameters
Sharing information between the caller function and
the called function is handled via parameters.
For example…
- printf passes information to the display (from the program)
- scanf passes information into the program by reading
characters from the keyboard
16 University of Oulu
Functions
A function must be defined before it can be called.
A common format for a function definition…
/* Comments for the function */
17 University of Oulu
• The comment for a function should
Functions provide all information needed to use
the function
• The functionality of the function
• Any conditions or restrictions to the use of the
function.
19 University of Oulu
• A function prototype (a function
Function declaration) is a header row ending
prototype with a semicolon.
• A function prototype must be defined
before it is used
• If a function is defined after the main
function (or alternatively in another
A compiler uses the prototype file), the function prototype has to be
to check the correctness of a defined before the main function.
function call • A compiler uses the prototype to
check the correctness of a function
call, to see whether the call mathes
the definition.
• Number of parameters for the function
• Order of parameters for the function
• Types of parameters for the function
20 University of Oulu
Function prototype
Example
A program simulating a cat…
21 University of Oulu
Function prototype
Example
The function
calculateAndDisplaySqrt receives
data from the caller function
(main) in the call (double
number).
The function does not return
anything (void).
22 University of Oulu
Functions
In the previous example…
• The function calculateAndDisplaySqrt receives a copy of the argument myValue’s value in
the parameter number.
• The value of the number is passed on to the library function sqrt (defined in math.h)
• The function sqrt calculates the square root of the number given as a parameter
• The function sqrt returns the value to the function calculateAndDisplaySqrt
• The function calculateAndDisplaySqrt saves the value to the variable result
• The values of the variables number and result are passed on to function printf
• The function printf will print the values to the screen.
Note - when arguments are passed by value, a copy of the argument’s value is made and passed
to the called function. Changes to the copy (in the called function) do not affect an original
variable’s value in the caller.
23 University of Oulu
Functions Passing arguments by value
25 University of Oulu
Prototype ! Functions
Example
Calculating the factorial of the
numer n (!n), where n is an
integer that is greater than or
equal to 0.
Functions
Arguments vs. parameters
26 University of Oulu
Functions
In the previous example, let’s assume the given integer number is 5 (line 11).
When the function myFactorial is called (line 13)…
result = myFactorial(number);
… the true parameter in the function call is the variable number (line 13).
The formal parameter n (line 23) receives the value 5 (from the variable number) when the body
of the function myFactorial is executed.
The calculated value, stored in the variable result is returned to the caller (main function) with the
return statement (line 32)…
return (result);
In the main function, the returned value is stored in the local variable result.
27 University of Oulu
Functions
Example
28 University of Oulu
• The number of true and formal
Functions parameters must match
Important! • The data types of the true and
formal parameters must match
• The order of parameters for the
true and formal parameters
must match
• The names of the true and
formal parameters do not have
to be the same
• A true parameter can be a
variable identifier, a constant
value or a statement
29 University of Oulu
Functions Logical functions
30 University of Oulu
Functions
Example
A logical function used as a
condition…
Functions
31 University of Oulu
Functions
An example program
A prime number is an integer (natural number), greater than
one that is not a product of two smaller numbers, i.e., cannot
be formed by multiplying two smaller natural numbers. (For
example, 5 is prime because the only ways of writing it as a
product, 1×5 or 5×1, involve the number 5 itself).
Requirements:
- Constant variable MAX for the upper limit for a number to be tested
- Input variable int n, an integer value to be tested
- Output variable int minDivisor, the smallest divisor for the number
32 University of Oulu
Functions
Design: Preliminary algorithm
33 University of Oulu
Functions As the number to be checked needs
to be greater than 1 and smaller than
MAX, we will refine the first step in
Read an integer value to the variable n
the algorithm...
if (n < 2)
Display an error message
”Read an integer value to be checked”
else
if (n < MAX)
execute statements 2 & 3 So, if the value is less than 2, we will display
an error message. If the value is more than
else
2 but less than MAX value, we will check
Display an error message the value. Otherwise (if the value is greater
than the MAX value), we will display an
error message.
34 University of Oulu
• We will design a function for the
Functions second step in the algorithm. We
will call the function getDivisor.
The function will return the
smallest divisor (greater than 1)
for the number n.
• The design and implementation of
the function getDivisor can now be
handled as a sub-problem of its
own.
• To solve the main problem, the
variable minDivisor in the main
function will store a value returned
from the function getDivisor.
35 University of Oulu
Functions We will refine the third step in
the algorithm, i.e., check the
value of the minDivirsor
(returned from the call to the
getDivisor)……
36 University of Oulu
Functions Implementation:
In the main function we will
call the function getDivisor,
as follows, and check its
output (the value of
minDivisor)…
minDivisor = getDivisor(n);
Example
Check if the given number n
(1 < n < 1000)
is a prime number or not…
38 University of Oulu
Functions
Analysis: We still need the function getDivisor which will
determine the smallest divisor (greater than 1) for the given
number n…
• The function getDivisor will find the divisor for the
number n by checking all integers starting from 2
• If the number 2 is not the divisor, we know that no other
even number can be a divisor for n. Thus, we can check for
the number 2 and only for the odd integers greater than 2.
39 University of Oulu
Functions
getDivisor
40 University of Oulu
Functions
Design: Preliminary algorithm
if n is an even number
min_divisor = 2;
else
min_divisor = 0; // We have not yet found the divisor
test_divisor = 3; // We will start testing from the number 3
41 University of Oulu
Please note, we will utilize the
Functions function
int isEvenNumber(int n) created
earlier…
if test_divisor > 𝒏
min_divisor = n
else if the division of n by test_divisor is zero
min_divisor = test_divisor
else
test_divisor is the next odd integer
42 University of Oulu
Functions
Example
Check if the given number n
(1 < n < 1000)
is a prime number or not.
Main function…
43 University of Oulu
Functions
Example: Check if the given number n
(1 < n < 1000)
is a prime number or not.
44 University of Oulu
Functions
Example: Check if the given number n
(1 < n < 1000)
is a prime number or not.
45 University of Oulu
Functions
An example program
A function findFactors which will display the prime factors for a given number, i.e., a number will be
presented as a multiplication of its prime factors. For example, a function call…
findFactors(84);
We will utilize the function getDivisor (written earlier, therefore utilizing modularization, re-use).
Please, study the following source code.
It is important to notice that there is no value to return from the function (a function of type void) and
that the call for the function getDivisor is embedded in the for-iteration structure.
46 University of Oulu
Functions
Example
Find prime factors for a given
number…
47 University of Oulu
Functions
Example
Find prime factors for a given
number…
48 University of Oulu
Functions
A statement can include several function calls.
𝒏 𝒏!
𝒓
=
(𝒏! 𝒏−𝒓! )
50 University of Oulu
Functions An example program of a
function returning multiple
values
Example
main function
52 University of Oulu
Functions
Example
breakNumber function
53 University of Oulu
Functions
Note the use of the parameters !!!
• The function breakNumber is of type void (no return statement)
• A value parameter value only passes the value
• The variables signChar, numerator and decimal are local variables for the
main function. The function breakNumber will get the addresses of those
three variables in the function call
• The function breakNumber uses the address parameters pSignAddr,
pNumeratorAddr and pDecimalAddr to pass the data back to main
function (note the * in front of the variable name)
• Operator & provides an address of the variable in the main memory
• The definition char *pSign tells the compiler the variable pSign holds an address to a variable of type char
(* is not part of the variable name)
54 University of Oulu
Functions
Passing arguments to and from functions by reference
• In the following example, we will be using the same address parameter to pass information from a caller
to a function and again from the function back to the caller
• An example will handle sorting of data (a common procedure in programming tasks)
The task: Our task is to write a program that reads three numbers (real numbers) and sorts those into ascending order
(from the smallest to the largest).
Analysis: As we need only three numbers, we will use variables num1, num2 and num3 to store the data. We will
compare the given values and store the largest one to num3 and the smallest one to num1.
Requirements:
• Input variables double num1, num2 and num3
• Output variables double num1, num2 and num3
55 University of Oulu
Functions
Design: Preliminary algorithm
56 University of Oulu
Functions
Refining the second step…
2.1. Compare the variables num1 and num2 and store the smaller into num1
and the larger to num2
2.2. Compare the variables num1 and num3 and store the smaller into num1
and the larger to num3
2.3. Compare the variables num2 and num3 and store the smaller into num2
and the larger to num3
In this example, it is essential to use address variables, i.e., pointers for passing
data.
57 University of Oulu
Functions
Example
main function
58 University of Oulu
Functions
Example
doSorting function
59 University of Oulu
Functions
doSorting
• After the first call for doSorting the formal parameter pSmaller
holds a value of the true parameter num1 (provided by the main
function), and the formal parameter pBigger holds a value of the
true parameter num2 (provided by the main function)
• The condition…
*pSmaller > *pBigger
… tests the pointers, whether the contents (values pointed by
those variables) need to be changed or not
60 University of Oulu
• In the function doSorting, the first
Functions assignment (when called the first time)…
temp = *pSmaller
… copies the value 5.0 to the variable
temp.
• The next assignment…
*pSmaller = *pBigger
… replaces the value pointed by
pSmaller (5.0) by the value pointed by
pBigger (-12.99)
• The last assignment…
*pBigger = temp
… copies the value of temp to the
variable pointed by pBigger (5.0).
61 University of Oulu
Functions
if (*pSmaller > *pBigger)
5.0
*pSmaller 5.0 *pSmaller *pSmaller *pSmaller
63 University of Oulu
Functions • The scope of an identifier is the
portion of the program in which
the identifier can be referenced.
Scope rules • The scope of a function begins
from the function header and
The four identifier scopes are continues to the end of the
• Function scope function (excluding identifiers that
• File scope
• Block scope and have the same name in local use).
• Function-prototype scope.
• All local and formal variables have
the scope from the function
header to the end of the function
(terminating right brace).
64 University of Oulu
Functions
Example
Example
main function
66 University of Oulu
Functions
Example
useLocal function
useStaticLocalfunction
useGlobal function
67 University of Oulu
Functions
Example
68 University of Oulu
FUNCTION
Libraries
University of Oulu
Function Libraries
• In C, there are many existing functions ready to use that have been
collected into function libraries, C standard libraries.
• As we have learned, we need to include the library in the program by
using #include pre-processor directive and providing the name of the
library in between the left angle bracket and the right angle bracket, i.e.,
between the less-than and greater-than signs (<>).
#include <stdio.h>
• A header file (file with postfix .h) includes prototypes for the functions.
The left and right angle bracket are an indication to the compiler that the
implementation for the functions is in the standard library directory.
70 University of Oulu
Function Libraries
C standard libraries (just few examples)
Header Explanation
<assert.h> Contains 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.
<limits.h> Contains the integral size limits of the system.
<math.h> Contains function prototypes for math library functions
<stdio.h> Contains function prototypes for the standard input/output library functions,
and information used by them.
<stdlib.h> Contains function prototypes for conversions of numbers to text and text to
numbers, memory allocation, random numbers and other utility functions.
<string.h> Contains function prototypes for string-processing functions.
<time.h> Contains function prototypes and types for manipulating the time and date.
71 University of Oulu
Function Libraries
Commonly used math library functions (math.h)
Function Description Example
sqrt(x) square root of x sqrt(9.0) is 3.0
log(x) natural logarithm of x (base e) log(7.389056) is 2.0
log10(x) logarithm of x (base 10) log10(10.0) is 1.0
fabs(13.5) is 13.5
fabs(x) absolute value of x as a floating-point number
fabs(-13.5) is 13.5
ceil(9.2) is 10.0
ceil(x) rounds x to the smallest integer not less than x
ceil(-9.8) is -9.0
rounds x to the largest integer not greater than floor(9.2) is 9.0
floor(x) floor(-9.8) is -10.0
x
pow(2, 7) is 128.0
pow(x, y) x raised to power y (x y)
pow(9, .5) is 3.0
72 University of Oulu
Function Libraries
Date and time functions (time.h)
‒ The header file time.h contains functions and types for manipulating the
time and date. The functions allow to ask for the date and time from the
operating system and convert time formats.
‒ In many environments, the date and time are expressed as seconds
that have elapsed since 1.1.1970 (00:00:00), also known as epoch time.
Function Description
stime() Sets the system’s idea of the time and date
time() Calculates the current calender time and encodes it into time_t format.
asctime() Returns a pointer to a string which represents the day and time of the structure timeptr.
Returns the processor clock time used since the beginning of an implementation defined era (normally
clock() the beginning of the program).
73
* See header time.h or related documentation for details and examples, how to use these functions. University of Oulu
Function Libraries
Common utility functions (stdlib.h)
Function* Description
rand() Returns a pseudo-random number in the range of 0 to RAND_MAX.
srand() This function seeds the random number generator used by the function rand.
exit() Causes the program to terminate normally.
abort() Causes an abnormal program termination.
malloc() Allocates the requested memory and returns a pointer to it.
Attempts to resize the memory block pointed to by ptr that was previously allocated
realloc()
with a call to malloc or calloc.
free() Deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
The command specified by string is passed to the host environment to be executed by
system()
the command processor.
qsort() Sorts an array (quicksort).
74
* See header stdlib.h or related documentation for details and examples, how to use these functions. University of Oulu
Function Libraries
Common functions for testing & mapping characters (ctype.h)
Function* Description
isalpha() This function checks whether the passed character is alphabetic.
iscntrl() This function checks whether the passed character is control character.
ispunct() This function checks whether the passed character is a punctuation character.
isspace() This function checks whether the passed character is white-space.
isupper() This function checks whether the passed character is an uppercase letter.
islower() This function checks whether the passed character is lowercase letter.
tolower() This function converts uppercase letters to lowercase.
toupper() This function converts lowercase letters to uppercase.
isdigit() This function checks whether the passed character is decimal digit.
75
* See header ctype.h or related documentation for details and examples, how to use these functions. University of Oulu
Function Libraries
Common functions for manipulating arrays of characters (string.h)
Function* Description
strcat() Combines two strings (appends one to the end of another).
strcmp() Compares two strings.
strcpy() Copies a string to another.
strncpy() Copies up to n first bytes of a string to another.***
Computes the length of the string str up to but not including the terminating null
strlen()
character.
strtok() Breaks the given string str into a series of tokens separated by the given delimiter.
Searches for the first occurrence of the given character c (an unsigned char) in the string
strchr()
pointed to, by the given argument str.
* See header string.h or related documentation for details and examples, how to use these functions.
76 *** strncpy does not always copy terminating null character! University of Oulu
Summary
A function returning a value is the simplest, thus prefer returning a value via return statement when possible
A function can receive data (input) using value and address parameters
A function and its caller can pass data (input & output) using value and address parameters
If a function is required to pass data back to the caller via parameters, then we need to use indirect referencing (address
parameters) i.e., pointers
Provide comments for a function where the functionality is complex or needs to be justified.
University of Oulu