7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 1/42
CS1010E Programming Methodology
Functions
Get this job done for me!
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 2/42
Lecture Overview
Top Down Approach to Problem Solving
Functions
basic idea
execution flow
prototype and declaration
scoping rules
C Standard Library
Math Library
[ CS1010E AY1112S1 Lecture 3 ]2
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 3/42
Top Down Approach
When solving large problems, it is hard to
come up with a detailed solution right away
A common approach is:
Specify the major steps of the algorithm
Review each major step and break it down into
smaller steps (step-wise refinement)
Repeat this process if needed until the steps are
well defined
This is known as Top Down Approach to
problem solving
3[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 4/42
Example 1
One way to calculate the PI π constant:
.........9
4
7
4
5
4
3
4
1
4−+−+−=π
When you compute the term using thesequence above:
1. PI starts as 4/1 (PI 4/1)
2. Subtract 4/3 from PI (PI PI – 4/3)
3. Add 4/5 to PI (PI PI + 4/5)
4. Subtract 4/7 from PI (PI PI – 4/7)
5. …
4
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 5/42
Example 1(cont’d)
A more general algorithm:
.........9
4
7
4
5
4
3
4
1
4−+−+−=π
even terms are
negative
odd terms are
positive
Denominator increases
by 2 every term
5
1. Initialize PI 4
2. Denom 3
3. nTerm 24. while nTerm is <= 1000
i. Calculate new term
ii. Update PI
iii. nTerm nTerm + 1
5. Show PI
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 6/42
PI Algorithm
6
a. Term 4 / Denom
1. Initialize PI 4
2. Denom 3
3. nTerm 2
4. while nTerm is <= 1000i. Calculate new term
ii. Update PI
iii. nTerm nTerm + 1
5. Show PI
a. If nTerm is even
PI PI – Term
b. If nTerm is odd
PI
PI + Term
First draft with only the major steps refinesMajor steps are further broken
down
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 7/42
Example 2: Anagrams
Two phrases are anagrams if one is formed
by rearranging the letters of the other,
disregarding spaces and punctuation marks.
“Debit card” = “Bad credit”
“The eyes” = “They see” “ Astronomer ” = “Moon starer ”
“ A telescope” = “To see place”
“ A decimal point” = “I’m a dot in place”
How do you determine if two words X and Y
are anagrams?7
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 8/42
Example: Anagram Algorithm
One possible solution using sorting
8
1. Read two words w1 and w2 from user
2. len1 = length of w1, len2 = length of w2
3. if len1 not equal len2
print "Not Anagrams" and stop
4. Sort w1 and w2 by alphabetical order
5. From position 0 to len1 - 1If w1position not equal w2position
print "Not Anagrams" and stop
6. print “They are Anagrams" and Stop
Steps to calculate the
length
Steps to sort a word
into alphabetical
order
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 9/42
Guidelines on Top Down Approach
As you learn more about C, you can see
clearer whether an algorithm step is
expressible in C with simple statement(s)
If it is not possible, break it down further to simpler
sub-problems
To learn a programming language is to know:
The expressive power of the language The limitations of the syntax
Such that high level algorithms can be translated
effectively
9[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 10/42
Functions
1. Using the top down approach:
A major step may correspond to many smaller
steps after refinement
If we place all the statements in one place, the
actual major step may no longer be obvious Large chunks of statements are hard to understand
2. Duplicated coding:
Some computations may be needed multiple times
in an algorithm
Error prone and wasteful to repeat the coding
10[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 11/42
Problem: A plate with 3 holes
Given the following plate, what is the area of
the shaded region after we drill 3 holes into
it?
11
a
b
c
Given:
R = radius of the plate Ra, Rb and Rc = radii
of the circles a, b and
c respectively[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 12/42
Algorithm: A plate with 3 holes
A simple algorithm could be:
12
1. Read R, Ra, Rb and Rc from user
2. Calculate Area = πR2
3. Calculate Areaa = πRa2
4. Calculate Areab = πRb2
5. Calculate Areac = πRc2
6. Calculate Areashaded = Area – Areaa- Areab - Areac
7. Show Areashaded
Duplicate coding!
Step 1 is also another source of duplicated
coding[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 13/42
Functions: The basic idea
A function in C: A program unit that performs a well defined task
May take input and produces output
Visualization:
13
Functioninput output
sum
Example:
3
912
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 14/42
Function: Syntax
14
S Y N T A X
result_datatype function_name( [input parameters] )
{
[0 or more declaration statements]
[0 or more other statements]
[return statement]
}
function header
function body
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 15/42
Function Header Function header indicates:
Input (if any) Data type of output result (if any)
15
int sum ( int x, int y )
sum3
912
sum gives
integer result
sum takes two
integer inputs
Function Name is an identifier
The usual identifier naming rule applies
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 16/42
Function Header: Input Parameters
The syntax for input parameters is similar to
declaration statements: Note that the data type is required before every
identifier
16
S Y N T A
X
datatype id1, datatype id2, ...
If the function does not take in any input
You can leave the input parameters blank
OR, you can use void
void is a special data type that means "Nothing"
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 17/42
Function Header: Output Data Type
You need to specify the type of values that a
function will produce
If the function does not return anything, you mustuse a void to indicate that
A function can return at most 1 result directly
Examples of function headers:
17
double areaOfCircle( double radius )
void print_info ( )
void print_info ( void )
void something ( int x, double y, int z )
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 18/42
Function Body: Statements
The statements in a function body:
Follow the rules we have learned so far
Additional variables can be declared
Computation can be expressed by statements
The input parameters:
Work as variables declared in this function
Only difference is that their values are initializedat the point of function call (more on this later)
18[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 19/42
Some Functions:
19
int sum ( int x, int y )
{int result;
result = x + y;
return result;
}
additional variable
x and y will have well defined values
return the calculated result
void print_info ( )
{ printf("Take a 4-digit number X\n");
printf("Rearrange the digits to get Y\n");
printf("Subtract and get R\n");
return;
}no need to return anything
Print instructions for theuser to follow
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 20/42
Functions in a Program
20
//Preprocessor directive not shown
int sum( int x, int y ){
int result;
result = x + y;
return result;
}
int main( )
{
int input1, input2;
//read input1 and input2 from user
//use sum() to add the two inputs
}
Any number of functions, complete
with header and body can beplaced before the mai n( )
Only restriction: You must
have the function declared
before its point of usage
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 21/42
Function Calls and Execution Flow
21
int sum( int x, int y )
{int result;
result = x + y;
return result;
}
int main( )
{
int input1, input2, output;
//read inputs
output = sum( input1, input2 );
printf("Sum is %d\n", output);
}
3.
4.
5.
2.
1.
6.
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 22/42
Function Calls: Parameters and Arguments
Actual arguments in a function call have a
1-to-1 correspondence with the formalparameters declared in function header
The effect is just like a variable declaration with
initialization in that function
22
int sum( int x, int y ){
............
}
sum( 3, 9 );//a function call
Effectively:int x = 3;
int y = 9;
actual arguments
formal parameter
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 23/42
Function Calls: Returned Result The result returned by a function: is a single value essentially replaces the function call and can be
used in normal arithmetic operations andassignment
23
result = sum( 3, 9 ) + sum( 5, 2 );
result = 12 + sum( 5, 2 );
result = 12 + 7;
result = 19;
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 24/42
Problem: A plate with 3 holes
24
#include <stdio.h>
#define PI 3.14159
double circleArea( double radius ){
double area = PI * radius * radius;
return area;
}
int main( ){
double rPlate, rA, rB, rC;
double areaPlate;
//read rPlate, rA, rB, rC – not shown
//calculate area of plate
areaPlate = circleArea( rPlate ) – circleArea( rA )– circleArea( rB ) – circleArea( rC );
//print areaPlate – not shown
return 0;
}
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 25/42
Functions: Scoping Rules
It is important to realise:
Variables declared in a function are only visible
within the function
25
int function( int x )
{int y;
... ...
}
int main( )
{
int x, y;
}
These variables are totallyindependent of each other.
A common misunderstanding is that by
changing a variable, it can directly affect
another variable of the same name. Thisis NOT true.
You can only pass information into a
function through the actual arguments
in a function call.
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 26/42
Functions: Prototype and Definition
User of a function only needs to know: Function name Number of input parameter and data type
Output data type
Description of function
Actual coding (the function body) is not essentialto the user
C Programming Language uses functionprototype to provide the essential information of a function
26[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 27/42
Function Prototype: Syntax and Usage
Note: Similar to function header
Semicolon at the end
Identifier of parameters optional
Usage: Ensure the prototype is declared before any actual
function call in the program27
S Y N T A X
rDatatype fname( [parameters datatype] );
E x a m p l e
int sum( int, int );
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 28/42
Function Definition Function definition is: the full coding of the function what we have seen so far
Separation of function prototype and definitionallows: Portability: You only need to show user the prototypes, not the full
coding
Ease of Maintenance: Function definition can be placed in a separate source
code file
Not covered in this course
28[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 29/42
Function Prototype: Example
29
int sum ( int, int );
// sum() takes two integer X, Y// and return the sum of X + Y
int main( )
{
.........
output = sum ( input1, input2 );.........
}
int sum ( int x, int y )
{int result;
result = x + y;
return result;
}
prototype
function call
definition
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 30/42
Example
30[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 31/42
Function Design: Guidelines
A good function should:
Rely only on its inputs to produce the output
Perform one task only
be reusable in your program and across programs
Use a function when:
You need to represent a complicated but well
defined step in the algorithm
Program Abstraction
You have found a generally useful task that
can/will be reused
Reusabil ity and Ease of Maintenance
31[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 32/42
Programming Style: Prototypes!
In this course, you need to:
Supply prototypes before the main() function
Supply definitions after the main() function
Additionally, you need to give a simplecomment to describe the function:
What are the inputs (if any)?
What is the purpose? What is the output (if any)?
A clear but simple description is needed
32[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 33/42
Programming Style: Modularity
You need to break your program into
reasonable modules (i.e. functions)
known as modularity
Use of functions will be evaluated: Is everything in mai n( ) ?
Is function useful in your program?
Is the design of function meaningful?
33[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 34/42
C Library
Useful predefined functions
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 35/42
C Standard Library Library:
A collection of functions Prototypes are organized into a header f ile (XXXX.h)
Provides great portability and reusability: User only needs to include XXXX.h in their program to use
those functions
C Standard Library: A set of libraries specified by C specification
All compliant compilers must support them
Provides commonly used functionalities: Input / Output
Mathematical Functions
others ( more later )
35[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 36/42
Learning to use C Standard Library
As a user, we only need to know information
specified by the function prototype to use it
Our usage of printf(), scanf() are good
examples
We highlight a few useful mathematical
functions here
Learn more by browsing the online C reference
http://www.acm.uiuc.edu/webmonkeys/book/c_guide/
36[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 37/42
Square Root Function
37
P r o t o
t y p e
double sqrt( double x);
//return the square root of x
H E A D E
R
#include <math.h>
E x
a m p l e double result;
result = sqrt( 4.0 ); //result = 2.0
C o m p i l a t i o n
gcc yourFile.c -lm
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 38/42
Power Function
38
P r o t o
t y p e
double pow( double base, double exp );
//return the baseexp
H E A D E
R
#include <math.h>
E x
a m p l e double result;
result = pow( 2.0, 4.0 ); //result = 16.0
[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 39/42
A lot more……
Trigonometry functions: sine, cosine, etc….
Logarithm functions:
log10, loge, exponential, etc….
Ceiling, Floor, Absolution value etc….
Reminder: Learn to make use of standard library
Don’t reinvent the wheel
39[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 40/42
Some Math Library Functions
Some Useful Math Library Functions (compiled with –lm option)
function abs(x) from <stdlib.h>; the rest from <math.h>
40[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 41/42
Summary
C
E l e m e n t s
Function
- Header and Body
- Function call
- Prototype and Definition
Library
- Introduction to Math Library
P r o g r a m m i n g S t y l e
Separate Function Prototype and Definition
Give function description in comment
Modularity
41[ CS1010E AY1112S1 Lecture 3 ]
7/26/2019 L3 - Functions
http://slidepdf.com/reader/full/l3-functions 42/42
Reference
Problem Solving and Program Design in C” –
Jeri R.Hanly & Elliot B.Koffman, 6th Edition,Pearson
Chapter 3
Online C reference:http://www.acm.uiuc.edu/webmonkeys/book/c_guide/