CS1010E Programming Methodology
Functions
Get this job done for me!
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 ]
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
[ CS1010E AY1112S1 Lecture 3 ]
Example 1
One way to calculate the PI constant:
4 4 4 4 4
= + + .........
1 3 5 7 9
When you compute the term using the
sequence 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
Example 1(contd)
even terms are
negative
4 4 4 4 4
= + + .........
1 3 5 7 9
Denominator increases
by 2 every term
odd terms are
positive
A more general algorithm:
1. Initialize PI 4
2. Denom 3
3. nTerm 2
4. while nTerm is <= 1000
i. Calculate new term
ii. Update PI
iii. nTerm nTerm + 1
5. Show PI
5
PI Algorithm
1. Initialize PI 4
2. Denom 3
3. nTerm 2
4. while nTerm is <= 1000
i. Calculate new term
ii. Update PI
iii. nTerm nTerm + 1
5. Show PI
First draft with only the major steps
[ CS1010E AY1112S1 Lecture 3 ]
a. Term 4 / Denom
a. If nTerm is even
PI PI Term
b. If nTerm is odd
PI PI + Term
refines
Major steps are further broken
down
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 = Im a dot in place
How do you determine if two words X and Y
are anagrams?
7
Example: Anagram Algorithm
One possible solution using sorting
1. Read two words w1 and w2 from user
2. len1 = length of w1, len2 = length of w2
Steps to calculate the
length
3. if len1 not equal len2
print "Not Anagrams" and stop
4. Sort w1 and w2 by alphabetical order
Steps to sort a word
into alphabetical
order
5. From position 0 to len1 - 1
If w1position not equal w2position
print "Not Anagrams" and stop
6. print They are Anagrams" and Stop
[ CS1010E AY1112S1 Lecture 3 ]
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
[ CS1010E AY1112S1 Lecture 3 ]
Functions
Using the top down approach:
1.
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
Duplicated coding:
2.
Some computations may be needed multiple times
in an algorithm
Error prone and wasteful to repeat the coding
[ CS1010E AY1112S1 Lecture 3 ]
10
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?
a
b
c
[ CS1010E AY1112S1 Lecture 3 ]
Given:
R = radius of the plate
Ra, Rb and Rc = radii
of the circles a, b and
c respectively
11
Algorithm: A plate with 3 holes
A simple algorithm could be:
1. Read R, Ra, Rb and Rc from user
2. Calculate Area = R2
3. Calculate Areaa = Ra2
4. Calculate Areab =
Rb2
Duplicate coding!
5. Calculate Areac = Rc2
6. Calculate Areashaded = Area Areaa- Areab - Areac
7. Show Areashaded
Step 1 is also another source of duplicated
coding
[ CS1010E AY1112S1 Lecture 3 ]
12
Functions: The basic idea
A function in C:
A program unit that performs a well defined task
May take input and produces output
Visualization:
input
Function
output
Example:
3
9
[ CS1010E AY1112S1 Lecture 3 ]
sum
12
13
Function: Syntax
function header
result_datatype function_name( [input parameters] )
SYNTAX
{
[0 or more declaration statements]
[0 or more other statements]
[return statement]
}
function body
[ CS1010E AY1112S1 Lecture 3 ]
14
Function Header
Function header indicates:
Input (if any)
Data type of output result (if any)
3
9
sum takes two
integer inputs
sum
12
sum gives
integer result
int sum( int x, int y )
Function Name is an identifier
The usual identifier naming rule applies
[ CS1010E AY1112S1 Lecture 3 ]
15
Function Header: Input Parameters
The syntax for input parameters is similar to
declaration statements:
Note that the data type is required before every
identifier
SYNTAX
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 ]
16
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 must
use a void to indicate that
A function can return at most 1 result directly
Examples of function headers:
double areaOfCircle( double radius )
void print_info( )
void print_info( void )
void something( int x, double y, int z )
[ CS1010E AY1112S1 Lecture 3 ]
17
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 initialized
at the point of function call (more on this later)
[ CS1010E AY1112S1 Lecture 3 ]
18
Some Functions:
int sum( int x, int y )
{
additional variable
int result;
result = x + y;
x and y will have well defined values
return result;
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;
}
[ CS1010E AY1112S1 Lecture 3 ]
Print instructions for the
user to follow
no need to return anything
19
Functions in a Program
//Preprocessor directive not shown
int sum( int x, int y )
{
int result;
result = x + y;
return result;
Any number of functions, complete
with header and body can be
placed before the main()
int main( )
{
int input1, input2;
//read input1 and input2 from user
//use sum() to add the two inputs
Only restriction: You must
have the function declared
before its point of usage
}
[ CS1010E AY1112S1 Lecture 3 ]
20
Function Calls and Execution Flow
int sum( int x, int y )
{
3.
int result;
result = x + y;
return result;
4.
int main( )
{
int input1, input2, output;
1.
//read inputs
2.
5.
output = sum( input1, input2 );
printf("Sum is %d\n", output);
6.
}
[ CS1010E AY1112S1 Lecture 3 ]
21
Function Calls: Parameters and Arguments
formal parameter
int sum( int x, int y )
{
............
}
sum( 3, 9 );
Effectively:
int x = 3;
int y = 9;
//a function call
actual arguments
Actual arguments in a function call have a
1-to-1 correspondence with the formal
parameters declared in function header
The effect is just like a variable declaration with
initialization in that function
[ CS1010E AY1112S1 Lecture 3 ]
22
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 and
assignment
result = sum( 3, 9 ) + sum( 5, 2 );
result = 12 + sum( 5, 2 );
result = 12 + 7;
result = 19;
[ CS1010E AY1112S1 Lecture 3 ]
23
Problem: A plate with 3 holes
#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 ]
24
Functions: Scoping Rules
It is important to realise:
Variables declared in a function are only visible
within the function
int function( int x )
{
int y;
... ...
}
int main( )
{
int x, y;
}
[ CS1010E AY1112S1 Lecture 3 ]
These variables are totally
independent of each other.
A common misunderstanding is that by
changing a variable, it can directly affect
another variable of the same name. This
is NOT true.
You can only pass information into a
function through the actual arguments
in a function call.
25
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 essential
to the user
C Programming Language uses function
prototype
to provide the essential information of a function
[ CS1010E AY1112S1 Lecture 3 ]
26
SYNTAX
rDatatype fname( [parameters datatype] );
Example
Function Prototype: Syntax and Usage
int sum( int, int );
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 program
[ CS1010E AY1112S1 Lecture 3 ]
27
Function Definition
Function definition is:
the full coding of the function
what we have seen so far
Separation of function prototype and definition
allows:
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
[ CS1010E AY1112S1 Lecture 3 ]
28
Function Prototype: Example
prototype
int sum( int, int );
// sum() takes two integer X, Y
// and return the sum of X + Y
int main( )
{
.........
output = sum( input1, input2 );
.........
function call
}
int sum( int x, int y )
{
definition
int result;
result = x + y;
return result;
}
[ CS1010E AY1112S1 Lecture 3 ]
29
Example
[ CS1010E AY1112S1 Lecture 3 ]
30
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
Reusability and Ease of Maintenance
[ CS1010E AY1112S1 Lecture 3 ]
31
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 simple
comment 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
[ CS1010E AY1112S1 Lecture 3 ]
32
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 main() ?
Is function useful in your program?
Is the design of function meaningful?
[ CS1010E AY1112S1 Lecture 3 ]
33
C Library
Useful predefined functions
C Standard Library
Library:
A collection of functions
Prototypes are organized into a header file (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 )
[ CS1010E AY1112S1 Lecture 3 ]
35
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/
[ CS1010E AY1112S1 Lecture 3 ]
36
Compilation
Example
Prototype
HEADER
Square Root Function
#include <math.h>
double sqrt( double x);
//return the square root of x
double result;
result = sqrt( 4.0 );
//result = 2.0
gcc yourFile.c -lm
[ CS1010E AY1112S1 Lecture 3 ]
37
Example
Prototype
HEADER
Power Function
#include <math.h>
double pow( double base, double exp );
//return the baseexp
double result;
result = pow( 2.0, 4.0 );
[ CS1010E AY1112S1 Lecture 3 ]
//result = 16.0
38
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
Dont reinvent the wheel
[ CS1010E AY1112S1 Lecture 3 ]
39
Some Math Library Functions
Some Useful Math Library Functions (compiled with lm option)
function abs(x) from <stdlib.h>; the rest from <math.h>
[ CS1010E AY1112S1 Lecture 3 ]
40
Programming Style
C Elements
Summary
Function
- Header and Body
- Function call
- Prototype and Definition
Library
- Introduction to Math Library
Separate Function Prototype and Definition
Give function description in comment
Modularity
[ CS1010E AY1112S1 Lecture 3 ]
41
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/
[ CS1010E AY1112S1 Lecture 3 ]
42