450 likes | 679 Views
CS1010: Programming Methodology http://www.comp.nus.edu.sg/~cs1010/. 0. Revision (1/3). #include and #define. int main( void ){ declaration statements; executable statements; return 0 ; }. Which of the following identifiers are valid? Int D) 1twothree
E N D
CS1010: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1010/
0. Revision (1/3) #include and #define int main(void){ declaration statements; executable statements; return0; } Which of the following identifiers are valid? Int D) 1twothree $&cts E) celsius _____ F) a*b int, float, double, char CS1010 (AY2013/4 Semester 1) • Basic form of C program • Preprocessor directives • Main function • Declaration statements • Data types • Identifiers for variable names • Executable statements • Input/Output: I/O statements (scanf and printf) • Compute: Assignment statements with arithmetic operations Week3 - 2
0. Revision (2/3) scanf(“%d”, &age); scanf(“%d %lf”, &age, &cap); Don’t forget the ampersand! printf(“Your age and CAP are %d and %f.\n”, age, cap); int a = 7; printf(“%d\n”,a); printf(“%3d\n”,a); printf(“%03d\n”,a); float b = 1.111100; printf(“%3f\n”,b) printf(“%3.2f\n”,b); 7 1.111100 7 1.11 007 CS1010 (AY2013/4 Semester 1) • scanf – read data from keyboard • printf – print message to screen • Additional formatting: Week3 - 3
0. Revision (3/3) kms = 1.609 * miles; a is 2 after assignment int a = 2.5; c = 3+6; b = c; a = b; a = b = c = 3+6; a = (b = (c = 3+6)); Equivalent! 5.0/9 or (float)5/9 gives 0.555556 Week3 - 4 CS1010 (AY2013/4 Semester 1) • Assignment statements • Truncate when assigning a real number to an int variable • Can be cascaded and is right associative • Arithmetic operations • Integer vs. Real number: 5 vs 5.0 • Truncate when dividing an integer by another • E.g., 5 / 9 gives 0
Exercise #3 from Last Week Write a program Week2_Freezer.c that estimates the temperature in a freezer (in Celsius) given the elapsed time (hours) since a power failure. Assume this temperature (T) is given by: where tis the time since the power failure. Anaysis: • What are the inputs (and their types)? • What are the outputs (and their types)? • What are the intermediate results (and their type)? CS1010 (AY2013/4 Semester 1) Week3 - 5
Exercise #3 from Last Week Write a program Week2_Freezer.c that estimates the temperature in a freezer (in Celsius) given the elapsed time (hours) since a power failure. Assume this temperature (T) is given by: where tis the time since the power failure. Algorithm • Enter hours and minutes • Compute time elapsed in hours 2.1 time hours + minutes / 60.0 • Compute temperature 3.1 temperature 4 * time * time / (time +2) - 20 4. Print temperature CS1010 (AY2013/4 Semester 1) Week3 - 6
Exercise #3 from Last Week CS1010 (AY2013/4 Semester 1) Week3 - 7
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 • Chapter 5 Functions CS1010 (AY2013/4 Semester 1) Week3 - 8
Week 3: Outline 0. Revision • Math functions • Exercise #1: Freezer (version 2) • Problem Solving • Case Study: Top-down Design • Exercise #2: A simple “drawing” program • Functions • Exercise #3: Speed of Sound (take-home) • Exercise #4: Magic Number (take-home) • Edit, Compile and Execute a Program • Return statement in main() CS1010 (AY2013/4 Semester 1) Week3 - 9
1. Math functions (1/2) CS1010 (AY2013/4 Semester 1) • To compute t2, use t*t or pow(t, 2) • pow(x, y) // A math function that computes x to the power of y • A few other math functions • abs(x): |x|, sqrt(x): , log10(x): lgx • To use math functions • For abs(x), include <stdlib.h> • For others, include <math.h> AND compile with –lm option • See Tables 3.3 and 3.4 (pages 88 – 89) for some math functions Week3 - 10
1. Math functions (2/2) Q: Since the parameters x and y in pow() function are of double type, why can we call the function with pow(t, 2)? CS1010 (AY2013/4 Semester 1) Some useful math functions Week3 - 11
2. Exercise #1: Freezer (version 2) CS1010 (AY2013/4 Semester 1) Write a C program Week3_Freezer_New.c that replaces the old formula with this: Time limit: 10 minutes Week3 - 12
Week 3: Outline 0. Revision • Math functions • Exercise #1: Freezer (version 2) • Problem Solving • Case Study: Top-down Design • Exercise #2: A simple “drawing” program • Functions • Exercise #3: Speed of Sound (take-home) • Exercise #4: Magic Number (take-home) • Edit, Compile and Execute a Program • Return statement in main() CS1010 (AY2013/4 Semester 1) Week3 - 13
3. Problem Solving (1/3) Determine problem features Analysis Given a problem, how to proceed to reach a working program? Rethink as appropriate Write algorithm Design Produce code Implementation Check for correctness and efficiency Testing CS1010 (AY2013/4 Semester 1) Week3 - 14
3. Problem Solving (2/3) • Top-down Design A trip to Japan! 1 5 Sightseeing in Japan 4 2 3 CS1010 (AY2013/4 Semester 1) Week3 - 15
3. Problem Solving (3/3) Analysis and Design Top-down Design stepwise refinement ( hierarchy of) sub-problems NO Problem Statement YES sub-problems can be implemented? structure chart Implementation & Testing Knowledge in data structure (mostly CS1020) Knowledge in C and its libraries Knowledge in algorithms CS1010 (AY2013/4 Semester 1) Week3 - 16
4. Case Study: Top-down Design (1/11) You work for a hardware company that manufactures flat washers. To estimate shipping costs, your company needs a program that computes the weight of a specified quantity of flat washers. rim area = outer area – inner area CS1010 (AY2013/4 Semester 1) Week3 - 17
4. Case Study: Top-down Design (2/11) Analysis: • To get total weight, we need weight of each washer x qty • To get weight of a washer, we need volumedensity • To get volume, we need its rim areathickness • To get rim area, we need outer area – inner area • To get outer area and inner area, we need d2 and d1 Required inputs: qty, density, thickness, d2, d1 Answer qty weight volume density thickness rim area outer area inner area rim area = outer area – inner area d2 d1 CS1010 (AY2013/4 Semester 1)
4. Case Study: Top-down Design (3/11) Design: Algorithm: • Read in qty, density, thickness, d2, d1 • Compute weight of a single washer 2.1 Compute inner_areaπ * (d1/2)2 2.2 Compute outer_areaπ * (d2/2)2 2.3 Compute rim_area inner_area –outer_area 2.4 Compute volume rim_areathickness • 2.5 Compute weight volume density • Compute total_weightweightqty • Print total_weight CS1010 (AY2013/4 Semester 1) Week3 - 19
4. Case Study: Top-down Design (4/11) Design: • Structure Chart • Documents the relationships among the sub-problems CS1010 (AY2013/4 Semester 1) Week3 - 20
4. Case Study: Implementation (5/11) Week3_Washers.c #include <stdio.h> #include <math.h> #define PI3.14159 int main(void) { double d1, // input: holecirclediameter d2, // input: big circle diameter thickness, // input density; // input int qty; // input doubleunit_weight, // single washer's weight total_weight, // a batch of washers' total weight outer_area, // area of big circle inner_area, // area of small circle rim_area; // single washer's rim area // ask for all the inputs printf("Inner diameter in cm: "); scanf("%lf", &d1); printf("Outer diameter in cm: "); scanf("%lf", &d2); printf("Thickness in cm: "); scanf("%lf", &thickness); printf("Density in grams per cubic cm: "); scanf("%lf", &density); printf("Quantity: "); scanf("%d", &qty); CS1010 (AY2013/4 Semester 1) Week3 - 21
4. Case Study: Implementation (6/11) Week3_Washers.c // compute weight of a single washer outer_area = pow(d2/2, 2) * PI; inner_area = pow(d1/2, 2) * PI; rim_area = outer_area - inner_area; unit_weight = rim_area * thickness * density; // compute weight of a batch of washers total_weight = unit_weight * qty; // output printf("Total weight of the batch of %d washers is %.2f grams.\n", qty, total_weight); return0; } gcc–Wall -lm Week3_Washers.c CS1010 (AY2013/4 Semester 1) Week3 - 22
4. Case Study: Creating Function (7/11) • Redundancy in the program // compute weight of a single washer outer_area = pow(d2/2, 2) * PI; inner_area = pow(d1/2, 2) * PI; doublecircle_area(double diameter) { returnpow(diameter/2, 2) * PI; } • Call this function as needed in the program //Compute area of circle with diameter d2 outer_area = circle_area(d2); //Compute area of circle with diameter d1 inner_area = circle_area(d1); CS1010 (AY2013/4 Semester 1) A function for computing area of circle Week3 - 23
4. Case Study: Creating Function (8/11) #include <stdio.h> #include <math.h> #define PI3.14159 int main(void) { // identical portion omitted for brevity // compute weight of a single washer outer_area = circle_area(d2); inner_area = circle_area(d1); rim_area = outer_area – inner_area; // identical portion omitted for brevity } double circle_area(double diameter) { returnpow(diameter/2, 2) * PI; } Function definition rim_area = circle_area(d2) – circle_area(d1); Calling circle_area(). CS1010 (AY2013/4 Semester 1) Week3 - 24
4. Case Study: Creating Function (9/11) Function header Parameters Return type Function name double circle_area(double diameter) { returnpow(diameter/2, 2) * PI; } Function body CS1010 (AY2013/4 Semester 1) • Components of a function definition • Header (or signature)consists of return type, function name, and parameters (names and types) • Return typeis the type of the value to be returned (or void if no value needs to be returned) • Function name follows the naming rule for identifiers • Parameters specifies the types of inputs and their names in this function • Function body contains code to perform the task and return statements if return type is not void Week3 - 25
4. Case Study: Calling a Function (10/11) outer_area = circle_area(d2); Value of d2 copied to parameter diameter double circle_area(double diameter) { returnpow(diameter/2, 2) * PI; } • Arguments need not be variable names; they can be constant values or expressions circle_area(12.3) // Compute area of circle with diameter 12.3 circle_area((a+b)/2) // Compute area of circle with diameter (a+b)/2, where a and b are variables CS1010 (AY2013/4 Semester 1) Values of arguments are copied into parameters Week3 - 26
4. Case Study: Function Prototype (11/11) Function definition Week3_WashersV2.c #include <stdio.h> #include <math.h> #define PI3.14159 double circle_area(double); int main(void) { // identical portion omitted for brevity // compute weight of a single washer rim_area = circle_area(d2) - circle_area(d1); unit_weight = rim_area * thickness * density; // identical portion omitted for brevity } double circle_area(double diameter) { returnpow(diameter/2, 2) * PI; } Function prototype CS1010 (AY2013/4 Semester 1) • Preferred practice: add function prototype • Before main() function • Parameter names may be omitted, but not their type Week3 - 27
5. Exercise #2: A simple “drawing” program (1/3) Problem: Write a program Week3_DrawFigures.c to drawa rocket shipa triangle + a rectangle + an inverted V a male stick figure a circle + a rectangle + an inverted V a female stick figure a circle + a triangle + an inverted V rocket male female Analysis: • No particular input needed, just draw the needed 3 figures • The problem can be broken down into three sub-problems, which in turn can be broken down into three sub-sub-problems. Design: • Algorithm: • Draw Rocket ship (Draw triangle, rectangle and inverted V) • Draw Male stick figure (Draw circle, rectangle and inverted V) • Draw Female stick figure (Draw circle, triangle and inverted V) CS1010 (AY2013/4 Semester 1) Week3 - 28
5. Exercise #2: A simple “drawing” program (2/3) Design (Structure Chart): female male rocket CS1010 (AY2013/4 Semester 1) Week3 - 29
5. Exercise #2: A simple “drawing” program (3/3) #include <stdio.h> voiddraw_rocket_ship(); void draw_male_stick_figure(); void draw_circle(); voiddraw_rectangle(); int main(void) { draw_rocket_ship(); printf("\n\n"); draw_male_stick_figure(); printf("\n\n"); return0; } void draw_rocket_ship() { } voiddraw_male_stick_figure() { } void draw_circle() { printf(" ** \n"); printf("* * \n"); printf("* * \n"); printf(" ** \n"); } voiddraw_rectangle() { printf("******\n"); printf(" * * \n"); printf("* * \n"); printf("* * \n"); printf("****** \n"); } Implementation (partial program) Write a complete program Week3_DrawFigures.c CS1010 (AY2013/4 Semester 1) Week3 - 30
Week 3: Outline 0. Revision • Math functions • Exercise #1: Freezer (version 2) • Problem Solving • Case Study: Top-down Design • Exercise #2: A simple “drawing” program • Functions • Exercise #3: Speed of Sound (take-home) • Exercise #4: Magic Number (take-home) • Edit, Compile and Execute a Program • Return statement in main() CS1010 (AY2013/4 Semester 1) Week3 - 31
6. Functions (1/5) • The instructions in a program are separated into functions. • In general, onesub-problem gives rise to one function. • Collectively, these functions produce the necessary output (if any) based on the input (if any). • A function maps zero or more input to zero or more output • Zero output through “void func ( … ) { … }” • One output through, e.g., “double func ( … } { …; return value; }” • More outputs through changing input values(to be covered later) • Return value (if any) from function call can (but need not) be assigned to a variable. CS1010 (AY2013/4 Semester 1) Week3 - 32
6. Functions (2/5) Syntax: Example (Week3_Sample.c): function comment return-type function-name (parameters) { declaration statements executable statements return statement (if any) } Notes: Precondition: conditions that should be true before calling function. CS1010 (AY2013/4 Semester 1) Week3 - 33
6. 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. • Matching of actual and formal parameters from left to right • Scope of formal parameters, local variables are within the function only • Provide function prototypeto let the compiler know whether a call is valid CS1010 (AY2013/4 Semester 1) Week3 - 34
6. Functions (4/5) Week3_Sample.c The complete program CS1010 (AY2013/4 Semester 1) Week3 - 35
6. Functions (5/5) • Advantage of using functions • Separation of concerns • Parallel development • Reusable code • Incremental implementation and testing CS1010 (AY2013/4 Semester 1) Week3 - 36
7. Exercise #3: Speed of Sound (take-home) Write a program Week3_SpeedOfSound.c that calculates the speed of sound (s) in air of a given temperature T (oF). Formula to compute the speed s in feet/sec: • Values are of type float. • You should have a function speed_of_sound() to compute and return the speed. Decide on its parameter(s). • Sample run (values printed in 2 decimal places): • Temperature in degree Fahrenheit: 95.8 • Speed of sound in air of 95.80 degree = 1924.92 ft/sec • This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week3 - 37
8. 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, adds up the odd-positioned digits. The right-most digit of the sum is the required answer. • For example, if input is 76524, then adding up odd-positioned digits (7 + 5 + 4), we get 16. The answer is 6. • You should have a function get_magic() to compute and return the answer. Decide on its parameter(s). What is the precondition of the function? • Sample run: • Enter 1st value: 76524 • Magic number = 6 • Enter 2nd value:8946 • Magic number = 5 • This exercise is also mounted on CodeCrunch CS1010 (AY2013/4 Semester 1) Week3 - 38
9. Edit, Compile and Execute a Program (1/3) CS1010 (AY2013/4 Semester 1) • Edit a program with Vim • Common commands: • enter insert mode (i), enter command mode (<ESC>) • save (:w<ENTER>), save & exit (:wq<ENTER>), exit without saving (:q!<ENTER>) • deleting a line (dd), • undo (u), redo (CTRL-R) • go to line number n (:n<ENTER>or nG) • copy and paste (vyp), cut and paste (vdp) • auto-indent (gg=G) • Read vim resources at http://www.comp.nus.edu.sg/~cs1010/2_resources/online.html • Have TWO terminal windows at the same time! • One for editing and one for compilation and execution. Week2 - 39
9. Edit, Compile and Execute a Program (2/3) CS1010 (AY2013/4 Semester 1) • Compile a program using gcc • Compile with –Wall to enable warnings gcc –Wall Week3_Freezer_New.c • Compile with –o to specify a name for the executable file gcc –Wall Week3_Freezer_New.c –o Freezer • Compile with –lm for math functions gcc –Wall –lm Week3_Freezer_New.c • Compilation error/warning messages from gcc • Filename:line_number:column_number:type: reason Week3_Freezer_New.c:20:1:error: expected ‘;’ before “}“ token Week2 - 40
9. Edit, Compile and Execute a Program (3/3) • Sample test data • E.g., invest1.in and invest1.out • Input redirection (<) • a.out< invest1.in • Output redirection (>) • a.out< invest1.in > myinvest1.out • File comparison (diff) • diffmyinvest1.outinvest1.out CS1010 (AY2013/4 Semester 1) Week3 - 41
10. return statement in main( ) (for reading only) • Our C programs have this header for main() function • int main(void) • You usually see this return statement in main() • return 0; • The value 0 is returned to the operating system (which is UNIX in our case) on which the program is run. This is called the status code of the program. • In UNIX, when a program terminates with a value of 0, it means a successful run. • You may optionally check the status code to determine the appropriate follow-up action. • You do not need to worry about this. CS1010 (AY2013/4 Semester 1) Week3 - 42
Summary for Today • Today’s most important lessons • Applying top-down design for problem solving • Knowing how to use built-in functions • Writing your own user-defined functions CS1010 (AY2013/4 Semester 1) Week3 - 43
Announcements/Things-to-do • Revise • Chapter 3 The Basic of C – Math Functions • Chapter 5 Functions • To prepare for next week’s lecture • Selection statements (if-else, switch) • Read Chapter 4 (Lessons 4.1 to 4.6) before you come for lecture • Deadlines • Trial lab: this Friday, 30 Aug, end of the day • Lab 1: next Saturday, 7 Sep, 9am • Lab 2: next next Saturday, 14 Sep, 9am CS1010 (AY2013/4 Semester 1) Week3 - 44