Top Banner
KK10103 – Computer Programming Chapter 3 : Top Down Design with Functions By Suraya Alias
37

KK10103 – Computer Programming

Feb 22, 2016

Download

Documents

Luce

KK10103 – Computer Programming. Chapter 3 : Top Down Design with Functions By Suraya Alias. Figure 3.2 Outline of Program Circle. 3.1 Building Programs from Existing Information. Case study Finding the Area and Circumference of a Circle 1) Problem Definition / Requirement - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Chapter 3

KK10103 Computer ProgrammingChapter 3 : Top Down Design with Functions

By Suraya AliasFigure 3.1 Edited Data Requirements and Algorithm for Conversion Program1-2

Figure 3.2 Outline of Program Circle1-3

3.1 Building Programs from Existing InformationCase studyFinding the Area and Circumference of a Circle1) Problem Definition / RequirementGet the radius of a circle. Compute and display the circles area and Circumference.2) AnalysisWhat are the data requirement and formula needed?Problem constantPI = 3.14159Problem Inputradius /*radius of a circle*/Problem Outputarea /*area of a circle*/Circum /*circumference of a circle*/Relevant formulaArea of a circle = X radiusCircumference of a circle = 2 X radius

1-43) DesignAlgorithm1) Get the circle radius2) Calculate the area3) Calculate the circumference4) Display the area and the circumferenceStep 2 needs refinement2.1) Assign PI * radius * radius to areaStep 3 needs refinement 3.1) Assign 2 * PI * radius to circum

1-5Figure 3.3 Calculating the Area and the Circumference of a Circle1-6

5) Implementation 6) Testing

Figure 3.3 Calculating the Area and the Circumference of a Circle (contd)1-7

Figure 3.4 Computing the Rim Area of a Flat Washer1-8

Figure 3.5 Flat Washer Program1-9

Figure 3.5 Flat Washer Program (contd)1-10

3.2 Library FunctionPredefined Function and Code ReuseBy reusing predefined functions such as to perform mathematical function is called code reuseCs standard math library using #include defines a function named sqrt that perform the square root computation

Example; y = sqrt(x), wheresqrt(x) is the function call,sqrt is the function name, (x) is the argument

Other functions are pow(x,y), log(x), exp(x), cos(x), tan(x), sin(x)

1-11Figure 3.6 Function sqrt as a Black Box1-12

1) Given y=sqrt(x);2) x=16.0, so function squareroot computes the 3) The function result, 4.0 is assigned to y

Figure 3.7 Square Root Program1-13

Figure 3.7 Square Root Program (contd)1-14

ExampleWe can use the C function pow(power) and sqrt to compute the roots of a quadratic equation in x of the form

/*compute two roots, root_1 and root_2, for disc > 0.0*/disc= pow(b,2)-4 * a * c;root_1=(-b+sqrt(disc))/2*a;root_2=(-b-sqrt(disc))/2*a;

1-15

Figure 3.8 Triangle with Unknown Side a1-16

3.3 Top-Down Design and Structure ChartsTop Down DesignProblem solving method where problems are break into sub problems, then the sub problems are solved to solve the original problem.Structure ChartA documentation tool that shows the relationships among the sub problems of a problem1-17Figure 3.9 House and Stick Figure1-18

Case study : Drawing Simple DiagramFigure 3.10 Structure Chart for Drawing a Stick Figure1-19

3.4 Function without ArgumentSyntax : fname();example: draw_circle();The empty parentheses after the function name indicate that draw_circle requires no argumentFunction prototypeA function must be declared before it can be referenced.One way is to insert a function prototype before the main functionA function prototype tells the C compiler the data type of the function, the function name and the information about the arguments that the function expects

1-203.4 Function without ArgumentForm : ftype fname(void);Example : void draw_circle(void);Use void as ftype if the function does not return a valueThe argument list (void) indicates that the function has no argumentThe function prototype must appear before the first call to the function

1-21Figure 3.11 Function Prototypes and Main Function for Stick Figure1-22

3.4 Function without ArgumentFunction DefinitionsSyntax : ftypefname (void){local declarationexecutable statements}1-23

Figure 3.12 Function draw_circle1-24

Figure 3.13 Function draw_triangle

1-25

Figure 3.14 Program to Draw a Stick Figure.(Placement of Functions in a Program)1-26

Figure 3.14 Program to Draw a Stick Figure (contd)1-27

Figure 3.15 Flow of Control Between the main Function and a Function Subprogram1-28

Advantages of Using Function Subprograms1) Procedural AbstractionA programming technique in which a main function consists of a sequence of a function calls and each function is implemented separately2) Reuse of Function subprogramThe function can be executed more than once in a programExample : function draw_intersect is called twiceDisplaying User InstructionsWe can use functions without argument to display message, display lines of program output or instruction to user.

1-29Figure 3.16 Function instruct and the Output Produced by a Call1-30

3.5 Function with Input ArgumentInput ArgumentsArguments used to pass information into a function subprogramOutput ArgumentArguments used to return results to the calling functionWe can also return a single result from a function by executing a return statement in the function bodyArgument make function subprogram more versatile

1-31Figure 3.17 Lego Blocks1-32

Figure 3.18 Function print_rboxed and Sample Run1-33

Void Functions with Input ArgumentsActual ArgumentAn expression used inside the parentheses of a function call, (135.68)Formal Parameter an identifier that represents a corresponding actual argument in a function definition (rnum) Figure 3.18 Function print_rboxed and Sample Run (contd)1-34

Figure 3.19 Effect of Executing print_rboxed(135.68);1-35

Figure 3.20 Function with Input Arguments and One Result1-36

Figure 3.21 Functions find_circum and find_area1-37

Figure 3.22 Effect of Executing circum = find_circum (radius);1-38

If PI = 3.14159, radius=10.0circum = find_circum(radius)C subtitute the actual argument used in the function call for the formal parameter r

Figure 3.23 Function scale1-39

Program Style Function Interface commentPre condition a condition assumed to be true before a function callPost condition a condition assumed to be true after a Function executes

Figure 3.24 Testing Function scale1-40

Actual Argument corresponds toFormal Parameternum_1xnum_2nFigure 3.24 Testing Function scale (contd)1-41

Argument List CorrespondenceThe number of actual arguments used in a call of a function must be the same as the number of formal parameters listed in the function prototypeThe order of arguments in the lists determines correspondence. The first actual argument corresponds to the first formal parameter, and so on.Each actual argument must be of a data type that can be assigned to the responding formal parameter with no unexpected loss of information

Testing functions using driverDriver is a short function written to test another function by defining its arguments, calling it and displaying its result The main function can act as a driver1-42Figure 3.25 Data Areas After Call scale(num_1, num_2);1-43

The function call scale(2.5,-2) returns the value 0.025 where (2.5 X 10)From the formula (x * scale_factor)scale_factor = pow(10, n)

New C Constructs1-44ConstructEffectFunction Prototype (void function without argument)void star_line (void);Describes star_line as a function with no result and no argumentFunction Prototype (function with argument and a result)double average (int n, double x);Describes average as function with a type double result, 2 arguments, one type int and one type doubleFunction Call Statement (void function without argument)star_line();Calls function star_line and causes it to begin executionFunction Call (function with argument and a result)money = average(num_kids, funds);Calls function average to compute a result that is stored in moneyFunction Definition (void function without arguments)voidstar_line(void) { printf(*\n*\n*\n*\n);}Defines star_line as a function that prints a vertical line of four asterisks.1-45ConstructEffectFunction Definition(function with arguments and a result)/**Returns the average of its 2 arguments*Pre : x and n are defined, x >= 0, n>0*Post : result is x / n*/doubleaverage (int n, double x);{ return (x/n)}

Defines average as a function that returns the result of dividing its second argument with its first argument