## Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

sg/~cs1010/

**Week 3: Top Down Design
**

Objectives: How to analyse, design, and implement a program How to break a problem into sub-problems with step-wise

refinement How to use built-in library functions How to create your own user-defined functions

**References: Chapter 3 The Basic of C – Math Functions
**

We will do Character File Input/Output another time

Chapter 5 Functions

CS1010 (AY2013/4 Semester 1)

Week3 - 2

Week 3: Outline (1/2)

1. Check List: vim and gcc

**2. Last Week‟s Exercise #3 (Week2_Freezer.c)
**

3. Math functions 4. Exercise #1: Freezer (version 2)

5. Problem Solving

6. Case Study: Top-down Design

Computing the weight of a batch of flat washers Incremental Refinement (some hierarchical chart) Top-down design (of program) with structure charts

7. Exercise #2: A simple “drawing” program

CS1010 (AY2013/4 Semester 1)

Week3 - 3

Exercise #3: Speed of Sound (take-home) 10.Week 3: Outline (2/2) 8.4 . Functions Syntax Precondition. postcondition Actual and Formal parameters Flow of control Function prototype 9. Exercise #4: Magic Number (take-home) CS1010 (AY2013/4 Semester 1) Week3 .

etc.comp. undo previous command (u). go to line number n (:n or nG).5 CS1010 (AY2013/4 Semester 1) . paste (p).edu. residing in your home directory Created by the setup program you executed at the Intro Workshop You may change the settings to control how vim works/looks Week3 . Very useful command: gg=G (auto-indent your C program!) Go to vim resources at http://www.1. go to word (eg: /abc to go to word abc). Check List: vim Have you been practising vim? Very important! Common commands: deleting a line/n lines (dd/ndd). insert at beginning of line (I). delete a word (dw). yanking a line/n lines (yy/nyy). insert (i). append at end of line (A).vimrc vim configuration file. append (a).sg/~cs1010/2_resources/online.nus.html . delete a character (x).

use the –o option (do this with care!): gcc –Wall welcome. Check List: gcc Compiling C programs Compile welcome.c To specify a name for the executable file.c with –Wall (all warnings) to produce a.out: gcc –Wall welcome.6 CS1010 (AY2013/4 Semester 1) .out.1. Week3 .c –o welcome Executable file will be named welcome instead of a. Learn to read compilation error messages from gcc It usually pinpoints the line (or its vicinity) where the error occurs Common compilation errors/warnings at this point Missing & (address operator) in scanf() function Forgot to use –lm option when program uses math functions Eg: ld: fatal: symbol referencing errors.

Assume this temperature (T) is given by: 4t 2 T t2 20 where t is the time since the power failure.2. Thinking about the algorithm: What are the variables (and their type) for input data? What are the variables (and their type) for output? Is there any formatting of output? What are the variables (and their type) for intermediate results? How to compute the result? CS1010 (AY2013/4 Semester 1) Week3 . Last Week’s Exercise #3 Write a program Week2_Freezer.7 .c that estimates the temperature in a freezer (in Celsius) given the elapsed time (hours) since a power failure.

3 and 3.3.h> AND Compile your program with –lm option (i. or the pow() function in the math library: pow(t. you need to See Tables 3. you may use t*t. gcc –lm …) To use math functions. Eg: scanf() and printf() – requires to include <stdio.8 . 2) pow(x.e. Math functions (1/2) In C.h> For t2.4 (pages 88 – 89) for some math functions CS1010 (AY2013/4 Semester 1) Week3 . there are many libraries offering functions for you to use. y) // computes x raised to the power of y Include <math.

Math functions (2/2) Some useful math functions Function abs(x) from <stdlib.h>. the rest from <math.3.h> CS1010 (AY2013/4 Semester 1) Week3 .9 .

Exercise #1: Freezer (version 2) Write a C program Week3_Freezer_New.10 .4.c that replaces the old formula with this: CS1010 (AY2013/4 Semester 1) Week3 .

11 . how to proceed to reach a working program? Review week #1: Determine problem features Analysis Rethink as appropriate Write algorithm Design Produce code Implementation Check for correctness and efficiency Testing CS1010 (AY2013/4 Semester 1) Week3 . Problem Solving (1/2) Given a problem.5.

Problem Solving (2/2) Analysis and Design stepwise refinement NO ( hierarchy of ) sub-problems problem statement sub-problems can be implemented? YES structure chart Implementation & Testing Knowledge in C and its libraries Knowledge in algorithms Knowledge in data structure (mostly CS1020) CS1010 (AY2013/4 Semester 1) Week3 .12 .5.

13 .6. your company needs a program that computes the weight of a specified quantity of flat washers. To estimate shipping costs. rim area = (d2/2)2 – (d1/2)2 CS1010 (AY2013/4 Semester 1) Week3 . Case Study: Top-down Design (1/12) You work for a hardware company that manufactures flat washers.

d1 should be given as inputs. Answer qty volume weight density rim area d2 d1 thickness rim area = (d2/2)2 – (d1/2)2 Week3 . we need its volume density To get volume. d2.14 CS1010 (AY2013/4 Semester 1) .6. we need d2 and d1 qty. we need its rim area thickness To get the rim area. density. Case Study: Top-down Design (2/12) Analysis: - To get the weight of a specified qty of washer. thickness. we need to know the weight of each washer To get the weight of a washer.

density.Choose the identifier names and data types Design: .6. Compute weight of a single washer 2.3 2. Output the calculated weight CS1010 (AY2013/4 Semester 1) Week3 .5 Compute the area of the (small) hole using d1 Compute the area of the (big) circle using d2 Subtract the big area from the small area to get the rim_area Compute volume = rim_area thickness Compute weight = volume density 3. d1) 2. Read in all the necessary inputs (qty. Compute the weight of the specified number of washer = weight qty 4.Algorithm (view in words): 1. d2. thickness.1 2.2 2.4 2.We define what the inputs and outputs are . Case Study: Top-down Design (3/12) Analysis: .15 .

16 d2? CS1010 (AY2013/4 Semester 1) . Case Study: Top-down Design (4/12) Design: .6.Algorithm (view in some hierarchical chart) Compute Total Weight Ask for all inputs Compute Weight Compute weight x qty Output total weight qty? Compute hole area (use d1) density? Compute big circle area (use d2) thickness? Compute rim area d1? Compute volume (use thickness) Compute weight (use density) Week3 .

d1.17 . Case Study: Top-down Design (5/12) Design: .6. d2 Compute Weight of a single washer Compute total Weight Output total weight Compute circle area CS1010 (AY2013/4 Semester 1) Week3 . density. thickness.Structure Chart a documentation tool that shows the relationship among the subproblems Compute Total Weight Input : qty.

printf("Outer diameter in cm: "). density. Case Study: Implementation (6/12) #include <stdio. d2. &density). &d2). printf("Thickness in cm: "). &thickness). int qty. scanf("%lf".c // // // // // // // // // // input: hole circle diameter input: big circle diameter input input input single washer's weight a batch of washers' total weight area of big circle area of small circle single washer's rim area // ask for all the inputs printf("Inner diameter in cm: "). inner_area. total_weight. scanf("%lf". &qty). rim_area. &d1). scanf("%lf". double unit_weight. printf("Density in grams per cubic cm: ").14159 int main(void) { double d1. scanf("%lf". Week3_Washers. outer_area. CS1010 (AY2013/4 Semester 1) Week3 .18 . printf("Quantity: ").h> #include <math. scanf("%d".6. thickness.h> #define PI 3.

unit_weight = rim_area * thickness * density.19 . return 0.2f grams. // output printf("Total weight of the batch of %d washers is %. // compute weight of a batch of washers total_weight = unit_weight * qty. qty.6.inner_area. 2) * PI.\n". inner_area = pow(d1/2.c gcc Week3_Washers. total_weight). rim_area = outer_area . } Week3_Washers. Case Study: Implementation (7/12) // compute weight of a single washer outer_area = pow(d2/2.c -lm CS1010 (AY2013/4 Semester 1) Week3 . 2) * PI.

For code reusability. } We can then call/invoke this function whenever we need it. Case Study: Creating Function (8/12) Note that area of circle is computed twice.6. 2) * PI. double circle_area(double diameter) { return pow(diameter/2. circle_area(d2) to compute area of circle with diameter d2 circle_area(d1) to compute area of circle with diameter d1 CS1010 (AY2013/4 Semester 1) Week3 .20 . it is better to define a function to compute area of a circle.

6.21 .h> #define PI 3.14159 double circle_area(double diameter) { return pow(diameter/2. } int main(void) { // identical portion omitted for brevity // compute weight of a single washer Function definition rim_area = circle_area(d2) . 2) * PI. unit_weight = rim_area * thickness * density. Case Study: Creating Function (9/12) #include <stdio.h> #include <math.circle_area(d1). // identical portion omitted for brevity } Calling circle_area() twice. CS1010 (AY2013/4 Semester 1) Week3 .

6. } Parameter Return type Function body Week3 . function name. 2) * PI. or underscore. Case Study: Creating Function (10/12) Components of a function definition Header (or signature): consists of return type.22 CS1010 (AY2013/4 Semester 1) . contains a return statement if return type is not void Function name double circle_area(double diameter) { return pow(diameter/2. digit characters. and a list of parameters (with their types) separated by commas Function names follow identifier rules (just like variable names) May consist of letters. but cannot begin with a digit character Return type is void if function does not need to return any value Function body: code to perform the task.

Value of d2 copied to parameter diameter Value of d1 copied to parameter diameter Arguments need not be variable names. they can be constant values or expressions circle_area(12.circle_area(d1).6. where a and b are variables CS1010 (AY2013/4 Semester 1) Week3 .23 . Case Study: Calling a Function (11/12) Values of arguments are copied into parameters rim_area = circle_area(d2) .3 circle_area((a+b)/2) To compute area of circle with diameter (a+b)/2.3) To compute area of circle with diameter 12.

2) * PI. } CS1010 (AY2013/4 Semester 1) Function definition Week3 .h> #define PI 3.6.circle_area(d1). but not their type Week3_WashersV2.c Function prototype #include <stdio. unit_weight = rim_area * thickness * density. Case Study: Function Prototype (12/12) Preferred practice: add function prototype Before main() function Parameter names may be omitted.14159 double circle_area(double).24 . // identical portion omitted for brevity } double circle_area(double diameter) { return pow(diameter/2. int main(void) { // identical portion omitted for brevity // compute weight of a single washer rim_area = circle_area(d2) .h> #include <math.

Algorithm (view in words): 1.There are common shapes shared by the 3 figures Design: . Exercise #2: A simple “drawing” program (1/3) Problem: .c to draw a rocket ship (which is a triangle over a rectangle. Draw Male stick figure (below Rocket ship) 3.No particular input needed. Draw Rocket ship 2. a male stick figure (a circle over a rectangle over an inverted V). Draw Female stick figure (below Male stick figure) CS1010 (AY2013/4 Semester 1) Week3 .Write a program Week3_DrawFigures.7.25 . just draw the needed 3 figures . and a female stick figure (a circle over a triangle over an inverted V) rocket male female Analysis: . over an inverted V).

7. Exercise #2: A simple “drawing” program (2/3) Design (Structure Chart): rocket male female Draw 3 Figures Draw Rocket Ship Draw Male Stick Figure Draw Female Stick Figure Draw Triangle Draw Rectangle Draw Inverted V Draw Circle Draw Rectangle Draw Inverted V Draw Circle Draw Triangle Draw Inverted V CS1010 (AY2013/4 Semester 1) Week3 .26 .

return 0. printf(" * * \n"). int main(void) { draw_rocket_ship(). \n").h> void void void void draw_rocket_ship(). printf("\n\n"). \n"). Exercise #2: A simple “drawing” program (3/3) Implementation (partial program) Week3_DrawFiguresPartial. draw_male_stick_figure().7.c CS1010 (AY2013/4 Semester 1) void draw_rectangle() { printf(" ****** \n"). draw_rectangle(). printf(" * * \n"). printf("\n\n"). printf(" * * \n"). draw_circle(). \n"). void draw_rocket_ship() { } void draw_male_stick_figure() { } void draw_circle() printf(" ** printf(" * * printf(" * * printf(" ** } { \n"). } Week3 . } Write a complete program Week3_DrawFigures.c #include <stdio. printf(" ****** \n"). draw_male_stick_figure().27 .

Week3 .Zero output through “void func ( … ) { … }” . each box in a structure chart.One output through.. e. gives rise to a function In mathematics.g. go to the address stored in the variable following the * to get the/put a value at that address Return value (if any) from function call can (but need not) be assigned to a variable.8. }” . a function maps some input values to a single (possibly multiple dimensions) output In C. a function maps some input values to zero or more output values . Functions (1/5) A program is a collection of functions to transform input (if any) to output (if any) In general. return value.28 CS1010 (AY2013/4 Semester 1) . which is a sub-problem. “double func ( … } { ….More outputs through changing input values (we‟ll cover this later) • • „&‟ – „address of‟ operator ‘*’ – „indirection‟ operator.

if any } Notes: Precondition: describes conditions that should be true before calling function.29 . Functions (2/5) Syntax: function interface comment ftype fname (formal parameter declaration list) Example (Week3_Sample. CS1010 (AY2013/4 Semester 1) Week3 .8.c): { local variable declarations executable statements // include return statements. Postcondition: describes conditions that should be true after executing function.

8. Matching of actual and formal parameters from left to right Scope of formal parameters.30 . Functions (3/5) Actual parameters (also arguments) are values passed to function for computation Formal parameters (or simply parameters) are placeholder when function is defined. local variables are within the function only Arrows indicate flow of control between main and a call to a function Provide function prototype as function may be used before (compiler sees) its definition: CS1010 (AY2013/4 Semester 1) Week3 .

8.c CS1010 (AY2013/4 Semester 1) Week3 .31 . Functions (4/5) The complete program Week3_Sample.

This allows us to switch between abstract and go to specific at ease to eventually solve the problem. Function allows a team of programmers working together on a large program – each programmer will be responsible for a particular set of functions. O: order.32 CS1010 (AY2013/4 Semester 1) . Functions (5/5) Use of functions allow us to manage a complex (abstract) task with a number of simple (specified) ones. Function allows incremental implementation and testing (with the use of driver function to call the function and then to check the output) Acronym NOT summarizes the requirements for argument list correspondence. Function is good mechanism to allow re-use across different programs.8. (N: number of arguments. Programmers use functions like building blocks. T: type) Week3 .

You should have a function speed_of_sound() to compute and return the speed. Sample run (values printed in 2 decimal places): Temperature in degree Fahrenheit: 95. Decide on its parameter(s).92 ft/sec Bring your program to class next week This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week3 .9.c that calculates the speed of sound (s) in air of a given temperature T (oF). Exercise #3: Speed of Sound (take-home) Write a program Week3_SpeedOfSound.80 degree = 1924.33 .8 Speed of sound in air of 95. Formula to compute the speed s in feet/sec: 5T 297 s 1086 247 Values are of type float.

34 . Decide on its parameter(s). You should have a function get_magic() to compute and return the answer. we get 16. then adding up the digits 4. Exercise #4: Magic Number (take-home) Write a program Week3_MagicNumber.c that reads two positive integers (with at most 5 digits) and for each. and 5. The answer is hence 6. 5 and 7. adds up the digits (from right) in positions 1. For example. The right-most digit of the sum is the required answer. What is the precondition of the function? Sample run: Enter Magic Enter Magic 1st value: 76524 number = 6 2nd value: 8946 number = 5 Bring your program to class next week This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week3 . if input is 76524. 3.10.

35 .Summary for Today Today‟s most important lessons Stepwise refinement to get structure chart Knowing how to use built-in functions Writing your own user-defined functions CS1010 (AY2013/4 Semester 1) Week3 .

switch) Read Chapter 4 (Lessons 4.6) before you come for lecture Week3 .nus. Do Discussion Questions on module website (“CA” “Discussion”) before you come for your discussion session: http://www.comp.1 to 4.36 CS1010 (AY2013/4 Semester 1) .html Revise Chapter 3 The Basic of C – Math Functions Chapter 5 Functions To prepare for next week‟s lecture: We will do Selection statements (if-else.Announcements/Things-to-do (1/2) Discussion classes starting this week (Friday).sg/~cs1010/3_ca/discussion.edu.

37 . 9am CS1010 (AY2013/4 Semester 1) Week3 .Announcements/Things-to-do (2/2) Lab #1 has been released Deadline: 7th September 2013. Saturday. 9am Lab #2 will be released next week Deadline: 14th September 2013. Saturday.

End of File .

- Chapter 06 Functions
- Custom BAPI creation.docx
- Understanding Functions by Dk Mamonai 09CE37
- Hfm Functions Library
- 14511492 Visual Basic ViVa Question
- Storage Classes 4
- alvdetails
- A pra ti al guide to omputer sim ulations
- Document 2
- TB0-110demo
- C Programming Quiz
- ALV Documentation and Examples
- Dynamic Analysis.pdf
- Procedure Function
- Packages
- BAT4 11 Manual
- Rajaravi Alv Material
- Synopsis Macro
- fprimer
- Macro Processor Notes
- Students Lecture Manual
- 10.1.1.39.625
- L3 - Functions_4
- Midterm.sp10
- Quickstart Tutorial ATMEL AVR Microcontrollers
- Programing Training Strung OKUMA-OSP100
- dogeball tutorial revised v2
- Visualarq Grasshopper Exercise 1
- AA9604v3manual-2.13-en1
- c and ds manuaL

- frbclv_wp1987-11.pdf
- Use of Linear Regression in Machine Learning for Ranking
- tmp82D3.tmp
- As NZS ISO IEC 15437-2003 Information Technology - Open Distributed Processing - Enhancements to LOTOS (E-LOT
- tmp2A89.tmp
- tmp664
- tmpD747
- R/C Soaring Digest - Sep 2006
- Huawei Sample prograamming Placement Paper Level1
- tmp9B1B.tmp
- NIIT Sample Technical Placement Paper Level1
- As ISO IEC 15444.1-2004 Information Technology - JPEG 2000 Image Coding System Core Coding System
- As NZS 4379.2-1996 Information Technology - Open Systems Interconnection - Remote Database Access SQL Special
- Mindtree Sample Programming Placement Paper Level-I
- tmp1E7B.tmp
- Firstsource Sample Technical Placement Paper Level1
- tmpB60C.tmp
- L&T Infotech Sample Programming Placement Paper Level1
- Tcs Technical Placement Paper
- ISRO Sample Programming Placement Paper Level1
- frbrich_wp15-10.pdf
- SISL Sample Programming Placement Paper Level1
- As NZS 62026.5-2001 Low-Voltage Switchgear and Controlgear - Controller-Device Interfaces (CDIs) Smart Distri
- tmpBDD4.tmp
- 3-Axis Motion Control of CNC Machine based on G-Code, M-Code using FPGA and also Apply Bezier Curve
- Logica CMG Sample Programming Placement Paper Level1
- As NZS 14882-1999 Programming Languages - C Plus Plus
- Hawk Technology Systems v. Pennsylvania State University
- As NZS 3827.1-1998 Lighting System Performance - Accuracies and Tolerances Overview and General Recommendatio
- HCL Sample Technical Placement Paper

- ChewMA1506-14 Ch3
- Plug Folw Reactor
- Additional Slides for CH1
- ChewMA1506-14 Ch4
- ChewMA1506-14 Ch1
- Summary of CH6
- ChewMA1506-14 Ch5
- Integrals Used in Chapter One
- ChewMA1506-14 Ch7
- Past Year Exam Q CH3
- Cantilevered Beam
- ChewMA1506-14 Ch2
- ChewMA1506-14 Ch6
- Why sinhx
- pass exam CH 8 Q
- MA1506CHAP2
- Review Ch8
- MA1506CHAP5
- MA1506CHAP3
- CH7 Slide 37 and Two New Slides
- MA1506CHAP7
- MA1506CHAP8
- ChewMA1506-14 Ch8
- Shear Not Parallel to Axis
- MA1506CHAP6
- Basic Laplace Transforms
- MA1506CHAP1
- Impulsive Force and Velocity
- MA1506CHAP4
- chapter-1-2014

Sign up to vote on this title

UsefulNot usefulClose Dialog## Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

Close Dialog## This title now requires a credit

Use one of your book credits to continue reading from where you left off, or restart the preview.

Loading