J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.

Slides:



Advertisements
Similar presentations
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
Programmer-defined Functions Development of simple functions using value and reference parameters JPC and JWD © 2002 McGraw-Hill, Inc.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Functions Computational assistants.
Chapter 5 Functions.
C++ Basics Prof. Shermane Austin. Learning Programming Language Basics Data Types – simple Expressions Relational and Logical Operators Conditional Statements.
Function basics – pp Computational assistants – improves clarity and enable software reuse. JPC and JWD © 2002 McGraw-Hill, Inc.
Computer Science 1620 Function Scope & Global Variables.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 06 (Part I) Functions and an Introduction to Recursion.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
C++ Programming: Basic Elements of C++.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
1 FUNCTIONS - I Chapter 5. 2 What are functions ? Large programs can be modularized into sub programs which are smaller, accomplish a specific task and.
CPS120: Introduction to Computer Science Functions.
1 COMS 261 Computer Science I Title: String Class Date: October 3, 2005 Lecture Number: 14.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
Chapter 6: Programmer- defined Functions Development of simple functions using value and reference parameters JPC and JWD © 2002 McGraw-Hill, Inc. Modified.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
Section 4 - Functions. All of the programs that we have studied so far have consisted of a single function, main(). However, having more than one function.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions Parameters passed by reference.
1 MODULAR DESIGN AND ABSTRACTION. 2 SPECIFYING THE DETAILS OF A PROBLEM INTO A RELATED SET OF SMALLER PROBLEMS.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Functions & Strings CIS Feb-06. Quiz 1.Write a function Prototype for the function findSmallest that takes three integers and returns an integer.
Functions. Predefined Functions C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
User-Written Functions
Programmer-defined Functions
Chapter 1.2 Introduction to C++ Programming
Predefined Functions Revisited
Programming Applications
Programmer-defined Functions
Functions and an Introduction to Recursion
Chapter 5 Functions.
Programmazione I a.a. 2017/2018.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
CS150 Introduction to Computer Science 1
Functions and an Introduction to Recursion
COMS 261 Computer Science I
CS150 Introduction to Computer Science 1
COMS 261 Computer Science I
Predefined Functions Revisited
Functions Imran Rashid CTO at ManiWeber Technologies.
COMS 261 Computer Science I
CS1201: Programming Language 2
Presentation transcript:

J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters

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

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

Ch 6 / Foil 4 Function Invocation cout << CircleArea(MyRadius) << endl; 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(). Actual parameter

Ch 6 / Foil 5 Simple Programs l Single file n Include statements n Using statements n Function prototypes n Function definitions l Functions use value parameter passing n Also known as pass by value or call by value –The actual parameter is evaluated and a copy is given to the invoked function

Ch 6/ Foil 6 #include 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 = ; return Pi * r * r; }

Ch 6 / Foil 7 Value Parameter Passing Rules l Formal parameter is created on function invocation and it is initialized with the value of the actual parameter l Changes to the formal parameter do not affect the actual parameter l 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 l There is a new activation record for each invocation l The name of the formal parameter is only known within its function l The formal parameter is destroyed when the function invocation completes l Activation record memory is automatically released at completion

Ch 6/ Foil 8

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

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

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

Ch 6 / Foil 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; }

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

#include 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; } Ch 6/ Foil 14

// 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; } Ch 6/ Foil 15

// 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; } Ch 6/ Foil 16

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

Ch 6 / Foil 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 }

Ch 6 / Foil 19 Name Reuse l If a nested block defines an object with the same name as enclosing block, the new definition is in effect in the nested block

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 } Ch 6/ Foil 20

Ch 6 / Foil 21 Global Scope l Objects that are not defined within a block are global objects l A global object can be used by any function in the file that is defined after the global object l It is best to avoid programmer-defined global objects n Exceptions tend to be important constants l 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 l Local objects can reuse a global object's name l Unary scope operator :: can provide access to global object even if name reuse has occurred

Ch 6 / Foil 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; }

Ch 6 / Foil 23 Integrating Quadratic Polynomials l 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 a i x i, 0  i  n, with the restriction that a n is not 0. a n x n + a n–1 x n–1 + … + a 2 x 2 + a 1 x + a 0 l The area under the curve along the x-axis interval (s, t) for f(x) is a n ( s n +1 - t n+1 ) + a n–1 ( s n - t n ) + … + a 1 (t 2 - s 2 )/2 + a 0 (t - s) l For a quadratic polynomial (degree 2) this equation reduces a 2 (t 3 - s 3 )/3 + a 1 (t 2 - s 2 )/2 +a 0 (t - s)

Ch 6 / Foil 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; }

#include // program 6.3 #include 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; }

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

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

Ch 6 / Foil 28 Using int Factorial(int n) { if (n == 0) { return 1; } else { return n * Factorial(n-1); } l 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.

Ch 6 / Foil 29 Recursion Visualization Consider cout << n ! = " << Factorial(3) << endl;