SlideShare a Scribd company logo
1 of 24
Chapter 3
Top-Down
Design with
Functions
Instructor:
Kun-Mao Chao
( 台大資工 趙坤
茂 )
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-2
Building Programs from Existing
Programs
• Programmers seldom start off with an empty program.
• Reasons:
– Most basic or frequently used functions have been written
by other programmers.
– If you write every function by yourself, the source code
may be messy and hard to maintained.
– Less code, less bugs.
– You have product (or homework) deadline.
– Many existing libraries have tune the performance, and
thus are more reliable and robust.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-3
The Previous miles-to-kilometers
Conversion Program
We have used some pre-written I/O functions provided in C.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-4
Predefined Functions and Code Reuse
• The primary goal of software engineering is to
write error-free code.
– Code reuse: reusing program fragments that have
been written and tested.
• C library functions provide most commonly
used functions.
– e.g., mathematical library <math.h>
• To use existing C library functions, we have to
include the header file of the corresponding
library.
– e.g., #include <math.h>
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-5
Some Mathematical C Library
Functions
Function Header File Description
abs(x) <stdlib.h> Return the absolute value of x
cos(x) <math.h> Return the cosine of angle x
exp(x) <math.h> Return the value of ex
pow(x, y) <math.h> Return the value of xy
sqrt(x) <math.h> Return the squre root of x
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-6
An Example: The Usage of sqrt
Function (1/2)
Suppose we want to write a program which
reads a double value from the user.
Then it computes and outputs the square root
of the double value.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-7
An Example: The Usage of sqrt
Function (2/2)
Invoke the sqrt
functions
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-8
Top-Down Design and Structure Charts
• Most likely a problem is complex, and we have
to break up the problem into subproblems.
• Top-down design is a method in which we
break a problem into subproblems, solve those
subproblems, and derive the solution for the
original problem.
• Structure chart is a documentation tool that
shows the relationships among the subproblems
of a problem.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-9
An Example: House and Stick Figures
House figure Stick figure
You are required to draw a house figure and a
female stick figure.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-10
An Example: House and Stick Figures
• The house consists of a triangle without its
base and a rectangle.
• The stick consists of a circle, a triangle, and a
triangle without its base.
• Suppose we are given four basic drawing
components (functions).
– A circle,
– parallel lines,
– a base line,
– and intersecting lines.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-11
Structure Chart for Drawing a Stick
Figure
Because the triangle is not a basic component, we have
to draw intersecting lines and a base to form a triangle.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-12
Declare Functions without Arguments
• One way that programmers implement top-down design
is by defining their own functions.
– Usually a subproblem is solved by a corresponding
subprogram.
• The programmer can create their own functions.
• Functions without arguments:
– Declaration: ftype fname(void);
– The identifier ftype specifies the data type of the function
result.
– Example: void fname(void);
– After fname() is called, the execution of the program
jumps to the subprogram defined by fname.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-13
An Example: Function Prototypes and
Main Function for Stick Figure (1/2)
The self-created functions must
be declared in advance.
Invoke declared
functions
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-14
An Example: Function Prototypes and
Main Function for Stick Figure (2/2)
The subprogram (or called subfunction, subroutine)
corresponds to the draw_circle function.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-15
Flow of Control Between the Main
Function and a Subprogram
1. When the computer executes a function call statement, it
transfers the control to the function.
2. The computer allocates memory for variables used in the
function and execute the statements in the function body.
3. After the execution of the function, the control is
returned to the calling function and the allocated memory
is released.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-16
Advantages of Using Function
Subprograms
• Procedural abstraction
– The main function consists of a sequence of
function calls.
– We defer implementation details until we are
ready to write the subprogram.
– We can focus on one function at a time.
• Reuse of function subprograms
– The subprograms can be executed more than once
in a program.
– Decrease the length of code and chance of error.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-17
Declare Functions with Arguments
• The arguments of a function are used to transfer
information between the calling and called
functions.
– Input arguments are used to pass information
into a subprogram from the calling function.
– Output arguments are used to return results to
the calling function.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-18
Void Functions with Input Arguments
• We can create functions that receive input arguments
but does not return any result.
– void fname(type param1, type param2, …);
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-19
Functions with Input Arguments and a
Single Result
• We can create functions which receive input arguments
and return a single result.
– type fname(type param1, type param2, …);
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-20
An Example: Functions with a Single
Input Argument and A Result (1/2)
This function receives a double input
argument and returns a double value.
This function receives a double input
argument and returns a double value.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-21
An Example: Functions with a Single
Input Argument and A Result (2/2)
• After finishing execution of the subprogram, the
returned result may be stored into a variable.
– After invoking and executing find_circum(radius), the
variable circum is equal to 62.8318.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-22
An Example: Functions with Multiple
Input Arguments and A Result
• Function scale multiplies the first input argument by
10 raised to the power indicated by the second input
argument.
– e.g., scale(2.5, 2) returns 2.5 * 102
= 250.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-23
Data Areas After Call scale(num_1,
num_2)
• The local
variables x, n, and
scale_factor can
not be accessed in
the main function.
• The variables
num_1 and
num_2 in the
main function can
not be accessed in
the scale function. The value of scale_factor
is not ready.
Copyright ©2004 Pearson
Addison-Wesley. All rights
reserved. 3-24
Homework #2
• Write a program to take a depth as input data.
• Compute and display the temperature in both
degree Celsius and degree Fahrenheit at this
depth inside the earth.
• Two useful formulas:
– Celsius = 10*(depth) + 20;
– Fahrenheit = 1.8*(Celsius) + 32;
• You are required to create two subfunctions to
compute the above two formulas respectively.
• Due date: to be determined by TA (demo in lab.
lecture)

More Related Content

Similar to Chapter03 Top Down Design with Function

Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
CS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdfCS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdfssuser034ce1
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Parallel Computing - Lec 6
Parallel Computing - Lec 6Parallel Computing - Lec 6
Parallel Computing - Lec 6Shah Zaib
 
MATLAB programming for engineers
MATLAB programming for engineersMATLAB programming for engineers
MATLAB programming for engineersJARossiter
 
Data structures and algorithms 2
Data structures and algorithms 2 Data structures and algorithms 2
Data structures and algorithms 2 Mark John Lado, MIT
 
Assignment 1 Hypothetical Machine SimulatorCSci 430 Int.docx
Assignment 1  Hypothetical Machine SimulatorCSci 430 Int.docxAssignment 1  Hypothetical Machine SimulatorCSci 430 Int.docx
Assignment 1 Hypothetical Machine SimulatorCSci 430 Int.docxjane3dyson92312
 
JavaOne2013: Implement a High Level Parallel API - Richard Ning
JavaOne2013: Implement a High Level Parallel API - Richard NingJavaOne2013: Implement a High Level Parallel API - Richard Ning
JavaOne2013: Implement a High Level Parallel API - Richard NingChris Bailey
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Mohamed El Desouki
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDeepikaV81
 
chapter8.ppt clean code Boundary ppt Coding guide
chapter8.ppt clean code Boundary ppt Coding guidechapter8.ppt clean code Boundary ppt Coding guide
chapter8.ppt clean code Boundary ppt Coding guideSanjeevSaharan5
 
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...Claire Webber
 

Similar to Chapter03 Top Down Design with Function (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functions
FunctionsFunctions
Functions
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
CS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdfCS-102 DS-class04a Lectures DS Class.pdf
CS-102 DS-class04a Lectures DS Class.pdf
 
Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
intro to c
intro to cintro to c
intro to c
 
Parallel Computing - Lec 6
Parallel Computing - Lec 6Parallel Computing - Lec 6
Parallel Computing - Lec 6
 
MATLAB programming for engineers
MATLAB programming for engineersMATLAB programming for engineers
MATLAB programming for engineers
 
Data structures and algorithms 2
Data structures and algorithms 2 Data structures and algorithms 2
Data structures and algorithms 2
 
Assignment 1 Hypothetical Machine SimulatorCSci 430 Int.docx
Assignment 1  Hypothetical Machine SimulatorCSci 430 Int.docxAssignment 1  Hypothetical Machine SimulatorCSci 430 Int.docx
Assignment 1 Hypothetical Machine SimulatorCSci 430 Int.docx
 
JavaOne2013: Implement a High Level Parallel API - Richard Ning
JavaOne2013: Implement a High Level Parallel API - Richard NingJavaOne2013: Implement a High Level Parallel API - Richard Ning
JavaOne2013: Implement a High Level Parallel API - Richard Ning
 
Function
FunctionFunction
Function
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++
 
Design and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptxDesign and Analysis of Algorithms.pptx
Design and Analysis of Algorithms.pptx
 
chapter8.ppt clean code Boundary ppt Coding guide
chapter8.ppt clean code Boundary ppt Coding guidechapter8.ppt clean code Boundary ppt Coding guide
chapter8.ppt clean code Boundary ppt Coding guide
 
Workshop on python
Workshop on pythonWorkshop on python
Workshop on python
 
Basics of cpp
Basics of cppBasics of cpp
Basics of cpp
 
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...
APPLIED PRODUCTIVITY TOOLS WITH ADVANCED APPLICATION TECHNIQUES CUSTOM ANIMAT...
 

More from Inocentshuja Ahmad (20)

Bottom up parser
Bottom up parserBottom up parser
Bottom up parser
 
7th lec overview - latest
7th lec   overview - latest7th lec   overview - latest
7th lec overview - latest
 
6th lec infrared slides
6th lec   infrared slides6th lec   infrared slides
6th lec infrared slides
 
5th lec ofdm
5th lec   ofdm5th lec   ofdm
5th lec ofdm
 
3rd lec fcss
3rd lec   fcss3rd lec   fcss
3rd lec fcss
 
2nd lec wireless terminologies
2nd lec   wireless terminologies2nd lec   wireless terminologies
2nd lec wireless terminologies
 
1st lec generations
1st lec   generations1st lec   generations
1st lec generations
 
4rth lec dsss
4rth lec   dsss4rth lec   dsss
4rth lec dsss
 
Mcq's
Mcq'sMcq's
Mcq's
 
Long questions
Long questionsLong questions
Long questions
 
Lecture notes on mobile communication
Lecture notes on mobile communicationLecture notes on mobile communication
Lecture notes on mobile communication
 
Gsm
GsmGsm
Gsm
 
Lecture5 mobile communication_short
Lecture5 mobile communication_short Lecture5 mobile communication_short
Lecture5 mobile communication_short
 
8th lec flow and error control
8th lec   flow and error control8th lec   flow and error control
8th lec flow and error control
 
Chapter 10:Risk and Refinements In Capital Budgeting
Chapter 10:Risk and Refinements In Capital BudgetingChapter 10:Risk and Refinements In Capital Budgeting
Chapter 10:Risk and Refinements In Capital Budgeting
 
Chapter 9:Capital Budgeting Techniques
Chapter 9:Capital Budgeting TechniquesChapter 9:Capital Budgeting Techniques
Chapter 9:Capital Budgeting Techniques
 
Chapter 5:Risk and Return
Chapter 5:Risk and ReturnChapter 5:Risk and Return
Chapter 5:Risk and Return
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
Email security &amp; threads
Email security &amp; threadsEmail security &amp; threads
Email security &amp; threads
 
File System FAT And NTFS
File System FAT And NTFSFile System FAT And NTFS
File System FAT And NTFS
 

Recently uploaded

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 

Recently uploaded (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

Chapter03 Top Down Design with Function

  • 2. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-2 Building Programs from Existing Programs • Programmers seldom start off with an empty program. • Reasons: – Most basic or frequently used functions have been written by other programmers. – If you write every function by yourself, the source code may be messy and hard to maintained. – Less code, less bugs. – You have product (or homework) deadline. – Many existing libraries have tune the performance, and thus are more reliable and robust.
  • 3. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-3 The Previous miles-to-kilometers Conversion Program We have used some pre-written I/O functions provided in C.
  • 4. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-4 Predefined Functions and Code Reuse • The primary goal of software engineering is to write error-free code. – Code reuse: reusing program fragments that have been written and tested. • C library functions provide most commonly used functions. – e.g., mathematical library <math.h> • To use existing C library functions, we have to include the header file of the corresponding library. – e.g., #include <math.h>
  • 5. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-5 Some Mathematical C Library Functions Function Header File Description abs(x) <stdlib.h> Return the absolute value of x cos(x) <math.h> Return the cosine of angle x exp(x) <math.h> Return the value of ex pow(x, y) <math.h> Return the value of xy sqrt(x) <math.h> Return the squre root of x
  • 6. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-6 An Example: The Usage of sqrt Function (1/2) Suppose we want to write a program which reads a double value from the user. Then it computes and outputs the square root of the double value.
  • 7. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-7 An Example: The Usage of sqrt Function (2/2) Invoke the sqrt functions
  • 8. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-8 Top-Down Design and Structure Charts • Most likely a problem is complex, and we have to break up the problem into subproblems. • Top-down design is a method in which we break a problem into subproblems, solve those subproblems, and derive the solution for the original problem. • Structure chart is a documentation tool that shows the relationships among the subproblems of a problem.
  • 9. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-9 An Example: House and Stick Figures House figure Stick figure You are required to draw a house figure and a female stick figure.
  • 10. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-10 An Example: House and Stick Figures • The house consists of a triangle without its base and a rectangle. • The stick consists of a circle, a triangle, and a triangle without its base. • Suppose we are given four basic drawing components (functions). – A circle, – parallel lines, – a base line, – and intersecting lines.
  • 11. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-11 Structure Chart for Drawing a Stick Figure Because the triangle is not a basic component, we have to draw intersecting lines and a base to form a triangle.
  • 12. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-12 Declare Functions without Arguments • One way that programmers implement top-down design is by defining their own functions. – Usually a subproblem is solved by a corresponding subprogram. • The programmer can create their own functions. • Functions without arguments: – Declaration: ftype fname(void); – The identifier ftype specifies the data type of the function result. – Example: void fname(void); – After fname() is called, the execution of the program jumps to the subprogram defined by fname.
  • 13. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-13 An Example: Function Prototypes and Main Function for Stick Figure (1/2) The self-created functions must be declared in advance. Invoke declared functions
  • 14. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-14 An Example: Function Prototypes and Main Function for Stick Figure (2/2) The subprogram (or called subfunction, subroutine) corresponds to the draw_circle function.
  • 15. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-15 Flow of Control Between the Main Function and a Subprogram 1. When the computer executes a function call statement, it transfers the control to the function. 2. The computer allocates memory for variables used in the function and execute the statements in the function body. 3. After the execution of the function, the control is returned to the calling function and the allocated memory is released.
  • 16. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-16 Advantages of Using Function Subprograms • Procedural abstraction – The main function consists of a sequence of function calls. – We defer implementation details until we are ready to write the subprogram. – We can focus on one function at a time. • Reuse of function subprograms – The subprograms can be executed more than once in a program. – Decrease the length of code and chance of error.
  • 17. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-17 Declare Functions with Arguments • The arguments of a function are used to transfer information between the calling and called functions. – Input arguments are used to pass information into a subprogram from the calling function. – Output arguments are used to return results to the calling function.
  • 18. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-18 Void Functions with Input Arguments • We can create functions that receive input arguments but does not return any result. – void fname(type param1, type param2, …);
  • 19. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-19 Functions with Input Arguments and a Single Result • We can create functions which receive input arguments and return a single result. – type fname(type param1, type param2, …);
  • 20. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-20 An Example: Functions with a Single Input Argument and A Result (1/2) This function receives a double input argument and returns a double value. This function receives a double input argument and returns a double value.
  • 21. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-21 An Example: Functions with a Single Input Argument and A Result (2/2) • After finishing execution of the subprogram, the returned result may be stored into a variable. – After invoking and executing find_circum(radius), the variable circum is equal to 62.8318.
  • 22. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-22 An Example: Functions with Multiple Input Arguments and A Result • Function scale multiplies the first input argument by 10 raised to the power indicated by the second input argument. – e.g., scale(2.5, 2) returns 2.5 * 102 = 250.
  • 23. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-23 Data Areas After Call scale(num_1, num_2) • The local variables x, n, and scale_factor can not be accessed in the main function. • The variables num_1 and num_2 in the main function can not be accessed in the scale function. The value of scale_factor is not ready.
  • 24. Copyright ©2004 Pearson Addison-Wesley. All rights reserved. 3-24 Homework #2 • Write a program to take a depth as input data. • Compute and display the temperature in both degree Celsius and degree Fahrenheit at this depth inside the earth. • Two useful formulas: – Celsius = 10*(depth) + 20; – Fahrenheit = 1.8*(Celsius) + 32; • You are required to create two subfunctions to compute the above two formulas respectively. • Due date: to be determined by TA (demo in lab. lecture)