760 likes | 898 Views
Top-Down Design with Functions and Classes By Dr. Awad Khalil Computer Science & Engineering Department. 3.1 Building Programs from Existing Information. Reuse of existing programs Develop program in stages Compile along the way Keep it small Comments to describe actions. Washers.cpp.
E N D
Top-Down Design with Functions and ClassesBy Dr. AwadKhalilComputer Science & Engineering Department
3.1 Building Programs from Existing Information • Reuse of existing programs • Develop program in stages • Compile along the way • Keep it small • Comments to describe actions
Washers.cpp // File: washers.cpp // Computes the weight of a batch of flat // washers. #include <iostream> using namespace std; int main() { const float PI = 3.14159; float holeDiameter; // input -
Washers.cpp float edgeDiameter; // input - diameter float thickness; // input - thickness float density; // input - density float quantity; // input - number float weight; // output - weight float holeRadius; // radius of hole float edgeRadius; // radius of outer edge float rimArea; // area of rim float unitWeight; // weight of 1 washer
Washers.cpp cout << "Inner diameter in centimeters: "; cin >> holeDiameter; cout << "Outer diameter in centimeters: "; cin >> edgeDiameter; cout << "Thickness in centimeters: "; cin >> thickness; cout << "Material density in grams per cubic centimeter: "; cin >> density; cout << "Quantity in batch: "; cin >> quantity;
Washers.cpp // Compute the rim area. holeRadius = holeDiameter / 2.0; edgeRadius = edgeDiameter / 2.0; rimArea = PI * edgeRadius * edgeRadius - PI * holeRadius * holeRadius; // Compute the weight of a flat washer. unitWeight = rimArea * thickness * density; // Compute the weigh weight = unitWeight * quantity;
Washers.cpp // Display the weight cout << "The expected weight of the batch is " << weight; cout << " grams." << endl; return 0; }
Washers.cpp Program Output Inner Diameter in centimeters: 1.2 Outer Diameter in centimeters: 2.4 Thickness in centimeters: 0.1 Material density in grams per cubic centimeter: 7.87 Quantity in batch: 1000 The expected weight of the batch is 2670.23 grams
3.2 Library Functions • Goal of Structured Programming • Error free code • Reusability • Don’t reinvent the wheel • C ++ provides collection of functions • Organized in Libraries • Library examples Table 3.1
C++ Math Library • Functions in the Math library • sqrt cos sin pow • Examples Table 3.1 • Function use in Assignments y = sqrt (x); sqrt is function name x is function argument • Activated by a “function call” • Result of execution is assigned to variable y
C++ Math Library (cont) Function sqrt as a “black box” Square root computation • X is 16.0 Result is 4.0
C++ Library Functions • We can effectively utilize existing functions by learning to read function prototypes with the preconditions and postconditions. • Example prototype (or signature) • double sqrt(double x) • // PRE: x >= 0.0 • // POST: Returns the square root of x.
Preconditions and Postconditions • Comments that represents a contract between the implementor of a function and the user (client) of that function. • We'll look at two such comments: • Precondition: What the function requires. • Postcondition: What the function will do if the precondition is met.
Preconditions and Postconditions • The preconditions are the circumstances that must be true before the function can successfully fulfill the promised postconditions. • Example (Precondition abbreviates to PRE: double sqrt(double x); // PRE: x >= 0 // POST: Returns square root of argument X
SquareRoot.cpp // File: squareRoot.cpp // Performs three square root computations #include <cmath> // sqrt function #include <iostream> // i/o functions using namespace std; int main() { float first; float second; float answer;
SquareRoot.cpp // Get first number and display its square root. cout << "Enter the first number: "; cin >> first; answer = sqrt(first); cout << "The square root of the first number is " << answer << endl; // Get second number and display its square root. cout << "Enter the second number: "; cin >> second; answer = sqrt(second); cout << "The square root of the second number is " << answer << endl;
SquareRoot.cpp // Display the square root of the sum of first // and second. answer = sqrt(first + second); cout << "The square root of the sum of both numbers is " << answer << endl; return 0; }
SquareRoot.cpp • Program Output • Enter the first number: 9 • The square root of the first number is 3 • Enter the second number: 16 • The square root of the second number is 4 • The square root of the sum of both numbers is 5
3.3 Top-Down Design and Structure Charts Original Problem Level 0 Level 1 Detailed subproblems Level 2
3.4 Functions without Arguments • Functions used in Top-Down Design • main() is just a function • called by OS • C++ program is a collection of Functions • top level function is called the main() • lower level functions • User Defined or Libraries • Example StkFigMn.cpp
StickFigure.cpp // File: stickFigure.cpp // Draws a stick figure #include <iostream> using namespace std; // Functions used ... void drawCircle(); // Draws a circle void drawTriangle(); // Draws a triangle void drawIntersect(); // Draws intersecting lines void drawBase(); // Draws a horizontal line
StickFigure.cpp int main() { // Draw a circle. drawCircle(); // Draw a triangle. drawTriangle(); // Draw intersecting lines. drawIntersect(); return 0; }
Function Calls • We can call a function and get results without knowing the implementation of that function. • pow(x, y) returns x to the yth power. • For now, we need not know exactly how a function is implemented. • However, we do need to know how to use the function.
Function Calls • This general form of a function call: function-name ( optional argument-list ); • Example function call: drawCircle (); • The function name is drawCircle • No arguments to the function
Function Prototype • This general form of a function prototype: type function-name ( optional argument-list ); • Example function prototype: void skipThree (); • Type • int - float - char • Name • ( ); • Descriptive comment
Function Definition • General form of a function definition: type function-name (optional argument-list) { local-declarations - function body executable-statements } • Example function definition: voiddrawTriangle ()
Function Definition void drawTriangle () { // Draw a triangle. drawIntersect (); drawBase (); } function header function body
StickFigure.cpp // Draws a circle void drawCircle() { cout << " * " << endl; cout << " * *" << endl; cout << " * * " << endl; } // end drawCircle
StickFigure.cpp void drawCircleChar(char symbol) { cout << " " << symbol << " " << endl; cout << " " << symbol << " " << symbol << endl; cout << " " << symbol << " " << symbol << endl; } // Draws a triangle void drawTriangle() { drawIntersect(); drawBase(); }
StickFigure.cpp // Draws intersecting lines void drawIntersect() { cout << " / \\ " << endl; cout << " / \\ " << endl; cout << " / \\" << endl; } // draws a horizontal line void drawBase() { cout << " -------" << endl; }
Order of Execution int main() { drawCircle(); drawTriangle(); drawIntersect(); return 0; } void drawCircle() { cout << “ * “ << endl; cout << “ * * “ << endl; cout << “ * * “ << endl; }
Function Advantages • Program team on large project • Simplify tasks • Each Function is a separate unit • Top-down approach • Procedural abstraction • Information hiding • Reuse (drawTriangle)
Abstraction • Abstraction: • Refers to the act of ignoring details to concentrate on essentials. • Allows us to use complicated things with little effort (CD players, automobiles, computers).
Displaying User Instructions • We still have not covered passing in and out of a function • Following example shows displaying info • instruct(); function call in main
Instruct.cpp • // DISPLAYS INSTRUCTIONS TO THE USER • // OF AREA/CIRCUMFERENCE PROGRAM • int instruct () • { • cout << "This program computes the • area and " << endl; • cout << "circumference of a circle. " << endl << endl; • cout << "To use this program, enter the • radius of the " << endl; cout << "circle after the prompt" << endl;
Instruct.cpp • cout << "Enter the circle radius: " << endl << endl; • cout << "The circumference will be computed • in the same ” << endl; • cout << "units of measurement as the radius. The area " << endl; • cout << "will be computed in the same units squared." << endl << endl; • }
Program Output This program computes the area and circumference of a circle. To use this program, enter the radius of the circle after the prompt Enter the circle radius: The circumference will be computed in the same units of measurement as the radius. The area will be computed in the same units squared.
3.5 Functions with Input Arguments • Functions used like building blocks • Build systems one functions at a time • Stereo Components • Use function return values and arguments to communicate between functions • Discuss AreaMain.cpp • Flow of arguments and returns
Function Call Form: fname (actual arg list); Example: scale (3.0, z);
Function Return • Functions must return a value unless declared as void Form: return expression; Example: return x * y;
Function Definition Form: type fname (formal arg list) { function body } Example: float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }
Function Prototype Form:type fname (formal arg type list); Example:float scale (float x, int n);
TestScale.cpp // File testScale.cpp // Tests function scale. #include <iostream> #include <cmath> using namespace std; // Function prototype float scale(float, int); int main() {
TestScale.cpp float num1; int num2; // Get values for num1 and num2 cout << "Enter a real number: "; cin >> num1; cout << "Enter an integer: "; cin >> num2; // Call scale and display result. cout << "Result of call to function scale is " << scale(num1, num2) << endl; return 0; }
TestScale.cpp float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }
Argument / Parameter List Correspondence • Functions can have more than 1 arg • Correspondence between Actual & Formal arguments Function call scale (3.0, z); Actual Argument Formal Argument 3.0 x z n
Argument / Parameter List Correspondence float scale(float x, int n) { float scaleFactor; scaleFactor = pow(10, n); return (x * scaleFactor); }
Argument / Parameter List Correspondence Function call scale (x + 2.0, y); Actual Argument Formal Argument x + 2.0 x y y
Argument / Parameter List Correspondence Function call scale (y, x); Actual Argument Formal Argument y x x y Watch for type matches in formal and actual arguments
Key Points • The substitution of the value of an actual argument in a function call for its corresponding formal argument is strictly positional. That is, the value of the first actual argument is substituted for the first formal argument; the second and so on