1 / 29

Programmer-defined functions

Programmer-defined functions. Development of simple functions using value parameters. Function Definition. Includes description of the interface and the function body Interface Similar to a function prototype, but parameters names are required Body

Download Presentation

Programmer-defined functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programmer-defined functions Development of simple functions using value parameters

  2. Function Definition • Includes description of the interface and the function body • Interface • Similar to a function prototype, but parameters names are required • Body • Statement list with curly braces that comprises its actions • Return statement to indicate value of invocation

  3. Function Definition Function name Formal parameter Return type float CircleArea (float r) { const float Pi = 3.1415; return Pi * r * r; } Local object definition Function body Return statement

  4. Function Invocation cout << CircleArea(MyRadius) << endl; Actual parameter Invocation is part of a larger expression. To process the invocation, the function that contains the insertion statement is suspended and CircleArea() does its job. The insertion statement is then completed using the value supplied by CircleArea().

  5. Simple Programs • Single file • Include statements • Using statements • Function prototypes • Function definitions • Functions use value parameter passing • Also known as pass by value or call by value • The actual parameter is evaluated and a copy is given to the invoked function

  6. Ch 6/ Foil 6 #include <iostream> #include <string> using namespace std; float CircleArea(float r); // main(): manage circle computation int main() { cout << "Enter radius: "; float MyRadius; cin >> MyRadius; float Area = CircleArea(MyRadius); cout << "Circle has area " << Area; return 0; } // CircleArea(): compute area of radius r circle float CircleArea(float r) { const float Pi = 3.1415; return Pi * r * r; }

  7. Value Parameter Passing Rules • Formal parameter is created on function invocation and it is initialized with the value of the actual parameter • Changes to the formal parameter do not affect the actual parameter • Whenever a formal parameter is referenced, the value used for the formal parameter is the one stored in the current activation record for the function • There is a new activation record for each invocation • The name of the formal parameter is only known within its function • The formal parameter is destroyed when the function invocation completes • Activation record memory is automatically released at completion

  8. Ch 6/ Foil 8

  9. PromptAndRead() // PromptAndRead(): prompt and extract next // integer int PromptAndRead() { cout << "Enter number (integer): "; int Response; cin >> Response; return Response; }

  10. Max() // Max(): return larger of a and b int Max(int a, int b) { if (a < b) { return b; } else { return a; } }

  11. Min() // Min(): return smaller of a and b int Min(int a, int b) { if (a > b) { return b; } else { return a; } }

  12. Sum() // Sum(): compute sum of integers in a ... b int Sum(int a, int b) { int Total = 0; for (int i = a; i <= b; ++i) { Total += i; } return Total; }

  13. Problem • Definition • Input two numbers that represent a range of integers and display the sum of the integers that lie in that range • Design • Prompt user and read the first number • Prompt user and read the second number • Determine the smaller of the two numbers • Determine the larger of the two numbers • Calculate the sum of integers in the range smaller...larger by adding in turn each integer in that range • Display the sum

  14. Ch 6/ Foil 14 #include <iostream> #include <string> using namespace std; int PromptAndRead(); int Min(int a, int b); int Max(int a, int b); int Sum(int a, int b); int main() { int FirstNumber = PromptAndRead(); int SecondNumber = PromptAndRead(); int Smaller = Min(FirstNumber, SecondNumber); int Larger = Max(FirstNumber, SecondNumber); int RangeSum = Sum(Smaller, Larger); cout << "The sum from " << Smaller << " to " << Larger << " is " << RangeSum << endl; return 0; }

  15. Ch 6/ Foil 15 // Min(): return smaller of a and b int Min(int a, int b) { if (a > b) return b; else return a; } // Max(): return larger of a and b int Max(int a, int b) { if (a < b) return b; else return a; }

  16. Ch 6/ Foil 16 // PromptAndRead(): prompt & extract next integer int PromptAndRead() { cout << "Enter number (integer): "; int Response; cin >> Response; return Response; } // Sum(): compute sum of integers in a ... b int Sum(int a, int b) { int Total = 0; for (int i = a; i <= b; ++i) { Total += i; } return Total; }

  17. Blocks and Local Scope • A block is a list of statements within curly braces • Blocks can be put anywhere a statement can be put • Blocks within blocks are nested blocks • An object name is known only within the block in which it is defined and in nested blocks of that block • A parameter can be considered to be defined at the beginning of the block corresponding to the function body

  18. Local Object Manipulation void f() { int i = 1; cout << i << endl; // insert 1 { int j = 10; cout << i << j << endl; // insert 1 10 i = 2; cout << i << j << endl // insert 2 10 } cout << i << endl; // insert 2 cout << j << endl; // illegal }

  19. Name Reuse • If a nested block defines an object with the same name as enclosing block, the new definition is in effect in the nested block

  20. Ch 6/ Foil 20 void f() { { int i = 1; cout << i << endl; // insert 1 { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a } cout << i << endl; // insert 1 } cout << i << endl; // illegal insert }

  21. Global Scope • Objects that are not defined within a block are global objects • A global object can be used by any function in the file that is defined after the global object • It is best to avoid programmer-defined global objects • Exceptions tend to be important constants • Global objects with appropriate declarations can even be used in other program files • cout, cin, and cerr are global objects that are defined in by the iostream library • Local objects can reuse a global object's name • Unary scope operator :: can provide access to global object even if name reuse has occurred

  22. Example int i = 1; int main f() { cout << i << endl; // insert 1 char i = 'a'; cout << i << endl; // insert a ::i = 2; cout << i << endl; // insert a cout << ::i << endl; // insert 2 return 0; }

  23. Integrating Quadratic Polynomials • A polynomial f(x) of degree n is a function whose value is the sum of n+1 terms where the terms are of the form aixi, 0  i  n, with the restriction that an is not 0. anxn + an–1xn–1 + … + a2x2 + a1x + a0 • The area under the curve along the x-axis interval (s, t) for f(x) is an (sn +1 - tn+1) + an–1 (sn - tn) + … + a1 (t2 - s2)/2 + a0 (t - s) • For a quadratic polynomial (degree 2) this equation reduces a2(t3 - s3)/3 + a1(t2 - s2)/2 +a0(t - s)

  24. QuadraticArea() double QuadraticArea(double a2, double a1, double a0, double s, double t) { double term2 = a2*(t*t*t - s*s*s)/3.0; double term1 = a1*(t*t - s*s)/2.0; double term0 = a0*(t - s); return term2 + term1 + term0; }

  25. #include <iostream> // program 6.3 #include <string> using namespace std; double QuadraticArea(double a2, double a1, double a0, double s, double t); int main() { cout << "Enter quadratic coefficients (n n n): "; double a2, a1, a0; cin >> a2 >> a1 >> a0; cout << "Enter interval of interest (n n): "; double s, t; cin >> s >> t; double Area = QuadraticArea(a2, a1, a0, s, t); cout << "The area of quadratic polynomial " << a2 << "x*x + " << a1 << "x + " << a0 << " for (" << s << ", " << t << ")" << " is " << QuadraticArea(a2, a1, a0, s, t) << endl; }

  26. Recursion • Recursion is the ability of a function to call itself. • Consider the mathematical function n! n! = n * (n-1) … * 2 * 1 is not mathematically precise because we use an ellipsis (…). • Consider the following formal definition • n! = 0, if n = 0 • n! = n * (n-1)!, if n > 0 • The factorial function is defined in terms of itself

  27. Consider #include <iostream> #include <string> using namespace std; int main() { cout << "Enter a positive integer: "; int n; cin >> n; cout << n << "! = " << Factorial(n) << endl; return 0; }

  28. Using int Factorial(int n) { if (n == 0) { return 1; } else { return n * Factorial(n-1); } } • C++ function mirrors the mathematical factorial definition • If the value of n is 0, the value 1 is returned. • Otherwise, the product of n and Factorial(n-1) is returned.

  29. Recursion Visualization • Consider cout << n ! = " << Factorial(3) << endl;

More Related