Presentation is loading. Please wait.

Presentation is loading. Please wait.

Modular Programming with Functions

Similar presentations


Presentation on theme: "Modular Programming with Functions"— Presentation transcript:

1 Modular Programming with Functions
Copyright © 2012 Pearson Education, Inc. Chapter 6 Modular Programming with Functions

2 Copyright © 2012 Pearson Education, Inc.
Outline Objectives Modularity Programmer-Defined Functions Parameter Passing Problem Solving Applied: Calculating a Center of Gravity Random Numbers Problem Solving Applied: Instrumentation Reliability Defining Class Methods Problem Solving Applied: Design of Composite Materials Numerical Technique: Roots of Polynomials* Problem Solving Applied: System Stability* Numerical Technique: Integration* Copyright © 2012 Pearson Education, Inc.

3 Copyright © 2012 Pearson Education, Inc.
Objectives Develop problem solutions in C++ containing: Functions from the standard C++ library. Programmer-defined functions. Functions that generate random numbers Simulation Techniques. Techniques for finding real roots to polynomials. Numerical integration techniques. Copyright © 2012 Pearson Education, Inc.

4 Copyright © 2012 Pearson Education, Inc.
Modularity Copyright © 2012 Pearson Education, Inc.

5 Copyright © 2012 Pearson Education, Inc.
Modularity A problem solution contains numerous functions. main() is a programmer defined function. main() often references functions defined in one of the standard libraries. main() can also call other programmer defined functions. Functions, or modules, are independent statement blocks that are written to perform a specialized task. Copyright © 2012 Pearson Education, Inc.

6 Copyright © 2012 Pearson Education, Inc.
Modules A C++ source program can be thought of as an ordered collection of executable tasks: input data analyze data output results In C++ these tasks can be performed using programmer defined functions and types. Copyright © 2012 Pearson Education, Inc.

7 Copyright © 2012 Pearson Education, Inc.
Abstraction Involves the use of functions, objects, procedures, etc., whose details of operation are not known. The inputs, outputs, and external (public) behaviors of these ‘black boxes’ is all that is needed to use them effectively. E.g. many people know how to use cell phones while being blissfully ignorant of Maxwell’s equations or the protocols used by the phone companies to complete phone calls. Copyright © 2012 Pearson Education, Inc.

8 Abstraction via Modularity
Useful in reducing the development time of software while increasing quality. Modules may be tested and written separately. Modules may be reused many times in a problem solution. Also in other problem solutions. Once tested, modules do not need to be retested before being reused in other problem solutions. Tend to yield shorter programs Copyright © 2012 Pearson Education, Inc.

9 Modular Problem Solutions
Complex problems can be broken down into sub tasks performed on and/or by objects, making it easier to implement in C++. Modular, object-oriented programs have significant advantages over writing the entire solution in main(): Multiple programmers Testing/Debugging/Maintaining Reduce duplication of code Copyright © 2012 Pearson Education, Inc.

10 Copyright © 2012 Pearson Education, Inc.
Functions Pre-defined standard libraries Other libraries (including your own!) User defined Copyright © 2012 Pearson Education, Inc.

11 Pre-defined Function (Example)
#include <iostream> #include <cmath> using namespace std; int main() { double angle; cout << “input angle in radians: “; cin >> angle; cout << “\nthe sine of the angle is “ << sin(angle) << endl; return 0; }//end main Copyright © 2012 Pearson Education, Inc.

12 Programmer-Defined Functions
Copyright © 2012 Pearson Education, Inc.

13 Copyright © 2012 Pearson Education, Inc.
Function Terminology Function Prototype describes how a function is called Function Call references and invokes (i.e. causes execution of) a function Function Arguments Expressions provided as parameters to function call Function Definition function header statement block Formal Parameters Variables defined in the function header and used in definition to access the function’s parameters Formal parameters must agree with arguments in order, number and data type. Copyright © 2012 Pearson Education, Inc.

14 Copyright © 2012 Pearson Education, Inc.
Functions Can be defined to: return a single value to the calling function. perform a data independent task. modify data in calling context via the parameter list (pass by reference.) Copyright © 2012 Pearson Education, Inc.

15 Copyright © 2012 Pearson Education, Inc.
Function Definitions Syntax: return-type function_name ( [parameter_list] ) { //statements } Examples int main() { cout << “Hello World!” << endl; return 0; } void drawBlock(ostream& out, int size) { for (int height = 0; height < size; height++) { for (int width = 0; width < size; width++) out << “*”; out << endl; Copyright © 2012 Pearson Education, Inc.

16 Copyright © 2012 Pearson Education, Inc.
Function Prototype In C++, identifiers must be defined before they may be referenced. Since the main function is the entry point for the application, we like to have it appear near the beginning of the program. But for it to be able to call functions, defining all the functions it calls first is a problem. A function prototype provides sufficient information for the compiler to process references to the function. The definition may then be provided later in the code. Copyright © 2012 Pearson Education, Inc.

17 Copyright © 2012 Pearson Education, Inc.
Function Prototype Syntax: return-type function_name ( [parameter_list] ); Examples Valid References Invalid References double sinc(double); double sinc(double x); double y(-5); sinc(y) sinc(1.5) sinc(10) sinc(0.0) sinc(“hello”) sinc(‘0’) sinc(cout) void clear(ostream&); clear(cout); cout << clear(cout); Copyright © 2012 Pearson Education, Inc.

18 Value Returning Functions
A value returning function returns a single value to the calling program. The function header declares the type of value to be returned. A return statement is required in the statement block. Copyright © 2012 Pearson Education, Inc.

19 Copyright © 2012 Pearson Education, Inc.
Example - Factorial In math: n! = n*(n-1)*(n-2)*…*1 n is a positive integer 0! is 1 by definition Copyright © 2012 Pearson Education, Inc.

20 Copyright © 2012 Pearson Education, Inc.
Example - Factorial //function definition: n! = n*(n-1)*(n-2)*…*1 // 0! is 1 by definition //Function factorial returns n! //Function factorial assumes n is non-negative int int factorial(int n) //function header { int nfactorial = 1; while (n>1) { nfactorial = nfactorial * n; n--; } //end while block return nfactorial; } //end factorial Copyright © 2012 Pearson Education, Inc.

21 Example – Calling Factorial Function
int factorial(int); //function prototype int main() { int n; cin >> n; if (n>=0) cout << n << "! is “ << factorial(n) << endl; //n is the argument of the //factorial function call else cout <<"not defined for negative numbers" << endl; return 0; } //end main Copyright © 2012 Pearson Education, Inc.

22 Copyright © 2012 Pearson Education, Inc.
Void Functions A void function declares void as a return type. A return statement is optional. If a return statement is used, it has the following form return; Copyright © 2012 Pearson Education, Inc.

23 Copyright © 2012 Pearson Education, Inc.
Example //scale data //alters a data set by applying a scale factor //to each member of the data set. void scaleData(vector<double>& n, double sf) { for (int i = 0; I < data.size(); i++) data[i] *= sf; return; // return statement is optional… } //end scaleData Copyright © 2012 Pearson Education, Inc.

24 Copyright © 2012 Pearson Education, Inc.
Parameter Passing Copyright © 2012 Pearson Education, Inc.

25 Copyright © 2012 Pearson Education, Inc.
Parameter Passing C++ supports two forms of parameter passing: Pass by value. Pass by reference. Copyright © 2012 Pearson Education, Inc.

26 Copyright © 2012 Pearson Education, Inc.
Pass by Value Pass by value is the default in C++ (except when passing arrays as arguments to functions). The formal parameter is a distinct variable initialized with the value of the argument. The argument is an expression that is evaluated when the function is called to determine the value of the formal parameter. Changes to the formal parameter do not affect the argument. Copyright © 2012 Pearson Education, Inc.

27 Example //Function Definition int fact(int); int fact(int num) //4
{ int nfact = 1; //5 while(num>1) nfact = nfact*num; num--; } return(nfact); //6 } //end fact int fact(int); int main() { int n, factorial; //1 cin >> n; //2 if(n>=0) factorial = fact(n); //3 cout << n <<"! is " << factorial << endl;//7 } //end if return 0; } //end main

28 Memory Snapshot: main() fact() //Function Definition 3 1
int fact(int); int main() { int n, factorial; //1 cin >> n; //2 if(n>=0) factorial = fact(n); //3 cout << n <<"! is " << factorial << endl;//7 } //end if return 0; } //end main //Function Definition int fact(int num) //4 { int nfact = 1; //5 while(num>1) nfact = nfact*num; num--; } return(nfact); //6 } //end fact call fact() Memory Snapshot: main() fact() 3 1 4-> int num 5-> int nfact 1 6 6-> ? ? 1-> int n int factorial ? 2 -> 3 return nfact Note: value of n in main has not changed. 3 -> 3 6 7 ->

29 Copyright © 2012 Pearson Education, Inc.
Pass by Reference Pass by reference allows modification of a function argument. Must append an & to the parameter data type in both the function prototype and function header void getDate(int& day, int& mo, int& year) Formal parameter becomes an alias for the argument. The argument must be a variable of a compatible type. Any changes to the formal parameter directly change the value of the argument. Copyright © 2012 Pearson Education, Inc.

30 Copyright © 2012 Pearson Education, Inc.
Example #include <iostream> using namespace std; void swap(double&, double&); //function prototype int main() { double x=5, y=10; swap(x,y); //function call; x y are arguments cout >> “x = “ << x << ‘,’ << “ y= “ << y << endl; return 0; } //end main Output is: x = 10, y = 5 Copyright © 2012 Pearson Education, Inc.

31 Copyright © 2012 Pearson Education, Inc.
Example //Function swap interchanges the values of //two variables void swap(double& x, double& y) { double temp; //local variable temp temp = x; x=y; y=temp; return; //optional return statement } //end swap Copyright © 2012 Pearson Education, Inc.

32 Memory Snapshot: main() swap() //Function Definition
void swap(double& x, double& y) { double temp;// temp = x; x=y; y=temp; return; //optional }//end swap Program Trace: pass by reference #include <iostream> using namespace std; void swap(double&, double&); //prototype int main() { double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0; } //end main Memory Snapshot: main() swap() ? double x double y double temp 5 5 double x double y 10 call swap()

33 Memory Snapshot: main() swap() //Function Definition
void swap(double& x, double& y) { double temp;// temp = x; x=y; y=temp; return; //optional }//end swap Program Trace: pass by reference #include <iostream> using namespace std; void swap(double&, double&); //prototype int main() { double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0; } //end main Memory Snapshot: main() swap() ? double x double y double temp 5 10 double x double y 10

34 Memory Snapshot: main() swap() //Function Definition
void swap(double& x, double& y) { double temp;// temp = x; x=y; y=temp; return; //optional }//end swap Program Trace: pass by reference #include <iostream> using namespace std; void swap(double&, double&); //prototype int main() { double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0; } //end main Memory Snapshot: main() swap() ? double x double y double temp 5 10 double x double y 5 return;

35 Memory Snapshot: main() //Function Definition
void swap(double& x, double& y) { double temp;// temp = x; x=y; y=temp; return; //optional }//end swap Program Trace: pass by reference #include <iostream> using namespace std; void swap(double&, double&); //prototype int main() { double x=5, y=10; swap(x,y); //x y are arguments cout << "x = " << x << ',' << " y= " << y << endl; return 0; } //end main Memory Snapshot: main() 10 Arguments have been modified double x double y 5

36 Storage Class and Scope
Scope refers to the portion of the program in which it is valid to reference a function or a variable Storage class relatesto the lifetime of a variable Copyright © 2012 Pearson Education, Inc.

37 Copyright © 2012 Pearson Education, Inc.
Scope Local scope - a local variable is defined within a function or a block and can be accessed only within the function or block that defines it Global scope - a global variable is defined outside the main function and can be accessed by any function within the program file. Copyright © 2012 Pearson Education, Inc.

38 Copyright © 2012 Pearson Education, Inc.
Storage Class – 4 Types automatic - key word auto - default for local variables Memory set aside for local variables is not reserved when the block in which the local variable was defined is exited. external - key word extern - default for global variables Memory is reserved for a global variable throughout the execution life of the program. static - key word static Requests that memory for a local variable be reserved throughout the execution life of the program. The static storage class does not affect the scope of the variable. register - key word register Requests that a variable should be placed in a high speed memory register. Copyright © 2012 Pearson Education, Inc.

39 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

40 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

41 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

42 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

43 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

44 Problem Solving Applied: Calculating the Center of Gravity
Copyright © 2012 Pearson Education, Inc.

45 Copyright © 2012 Pearson Education, Inc.
Random Numbers Copyright © 2012 Pearson Education, Inc.

46 Copyright © 2012 Pearson Education, Inc.
Random Numbers Numbers generated with particular properties. Minimum and maximum values, likelihoods of particular values, etc. Often required in solving engineering problems! Computers generate psuedo-random number sequences. Random number seed used to alter the generators current point in the sequence. Copyright © 2012 Pearson Education, Inc.

47 Copyright © 2012 Pearson Education, Inc.
Random Integers C++ rand() function Generates a random integer between 0 and RAND_MAX (which is defined in <cstdlib>). To generate integers between 0 and b, use rand()%(b+1) To generate integers between a and b, use rand()%(b-a+1) + a Uniformly distributed. All values in the range equally likely. void srand(unsigned int); sets the seed of the Random Number Generator Copyright © 2012 Pearson Education, Inc.

48 Copyright © 2012 Pearson Education, Inc.
Example Function /* * This function generates a random integer * between specified limits a and b (a<b). * */ int rand_int(int a, int b) { return rand()%(b-a+1) + a; } Copyright © 2012 Pearson Education, Inc.

49 Copyright © 2012 Pearson Education, Inc.
Example Function /* * This function generates a random double * between specified limits a and b (a<b). * */ double rand_double(double a, double b) { return ((double)rand()/RAND_MAX)*(b-a) + a; } Copyright © 2012 Pearson Education, Inc.

50 Problem Solving Applied: Instrumentation Reliability
Copyright © 2012 Pearson Education, Inc.

51 Problem Solving Applied: Instrumentation Reliability
In series, all three components must work for the system to work. If each component works properly 80% of the time, then the system will work properly 0.83 = 51.2% of the time. Copyright © 2012 Pearson Education, Inc.

52 Problem Solving Applied: Instrumentation Reliability
In parallel, at least one component must work for the system to work. If each component works properly 80% of the time, then the system will work properly 1-(0.2)3 = 99.2% of the time. Copyright © 2012 Pearson Education, Inc.

53 Problem Solving Applied: Instrumentation Reliability
Copyright © 2012 Pearson Education, Inc.

54 Problem Solving Applied: Instrumentation Reliability
Copyright © 2012 Pearson Education, Inc.

55 Problem Solving Applied: Instrumentation Reliability
Copyright © 2012 Pearson Education, Inc.

56 Defining Class Methods
Copyright © 2012 Pearson Education, Inc.

57 Copyright © 2012 Pearson Education, Inc.
Encapsulation The public interface of a well-defined data type provides a complete set of public methods for interacting with the object while hiding the implementation details of the data type. Typically, attributes of an object are hidden (private or protected) and the public interface includes support for those attributes through accessor and mutator methods. Copyright © 2012 Pearson Education, Inc.

58 Copyright © 2012 Pearson Education, Inc.
Accessor Methods Value-returning methods usually with no parameters. Purpose is to return the value of an attribute. Read-only access. ‘get’ methods by convention. Copyright © 2012 Pearson Education, Inc.

59 Copyright © 2012 Pearson Education, Inc.
Mutator Methods Void methods usually with one or more input parameters. Purpose is to change (mutate) the value of an attribute. Write-only access. ‘set’ methods by convention. Copyright © 2012 Pearson Education, Inc.

60 Problem Solving Applied: Design of Composite Materials
Copyright © 2012 Pearson Education, Inc.

61 Problem Solving Applied: Design of Composite Materials
Copyright © 2012 Pearson Education, Inc.

62 Problem Solving Applied: Design of Composite Materials
Copyright © 2012 Pearson Education, Inc.

63 Problem Solving Applied: Design of Composite Materials
Copyright © 2012 Pearson Education, Inc.

64 Problem Solving Applied: Design of Composite Materials
Copyright © 2012 Pearson Education, Inc.

65 Numerical Technique: Roots of Polynomials*
Copyright © 2012 Pearson Education, Inc.

66 Copyright © 2012 Pearson Education, Inc.
Roots of Polynomials A polynomial is generally expressed in the form: Find values of x such that f(x) = 0 Degree of the polynomial is N N roots (may be real or complex) Easy to find roots if polynomial is factored into linear terms. Copyright © 2012 Pearson Education, Inc.

67 Copyright © 2012 Pearson Education, Inc.
Incremental Search Search for roots in polynomial over an interval by breaking the interval into smaller subintervals such that function is negative on one end and positive on the other end. Thus there is at least 1 real root This is always an odd number of real roots Keep decreasing the interval size to ‘narrow in’ on one root. Copyright © 2012 Pearson Education, Inc.

68 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

69 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

70 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

71 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

72 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

73 Problem Solving Applied: System Stability*
Copyright © 2012 Pearson Education, Inc.

74 Newton-Raphson Method
Popular root-finding method using a function and its first derivative. Iteratively estimates a root from the function and its derivative. Usually requires fewer iterations. Copyright © 2012 Pearson Education, Inc.

75 Numerical Technique: Integration*
Copyright © 2012 Pearson Education, Inc.

76 Numerical Integration
Integration of a function over an interval computes the area under the graph of the function. Important relationships in engineering (e.g. distance, velocity, acceleration). Computable through several techniques. Copyright © 2012 Pearson Education, Inc.

77 Copyright © 2012 Pearson Education, Inc.
Trapezoidal Rule Approximate integral by breaking integration interval into subintervals and estimating area under the graph in each by a trapezoid. Copyright © 2012 Pearson Education, Inc.


Download ppt "Modular Programming with Functions"

Similar presentations


Ads by Google