unit 6
play

Unit 6 Thinking with Functions 2 Functions Overview Map - PowerPoint PPT Presentation

1 Unit 6 Thinking with Functions 2 Functions Overview Map ValidateInputs() Service Functions (aka procedures, Function Decomposition RetrieveMap() subroutines, or methods) are the unit of code decomposition and GetOverlayData()


  1. 1 Unit 6 Thinking with Functions

  2. 2 Functions Overview Map ValidateInputs() Service • Functions (aka procedures, Function Decomposition RetrieveMap() subroutines, or methods) are the unit of code decomposition and GetOverlayData() abstraction – Decomposition: Breaking programs Render() into smaller units of code – Abstraction: Generalizing an action Publish() or concept without specifying how the details are implemented

  3. 3 Recall: Walking a Square in Scratch • We can define a function (i.e. block of code) once and then "call" it any time we want to execute that block of code. • Can provide different input values (aka "arguments" / "parameters") and even get an output (aka "return" value) . 1 2 3

  4. 4 Function Signatures/Prototypes • We think of a function as a blackbox (don't know or care how it does the task a b internally) where we can provide inputs and get back a value max • A function has: – A name int max(int a, int b); – Zero or more input parameters Function Signature/Prototype – 0 or 1 return (output) values • We only specify the type • The signature (or prototype ) of a function specifies these aspects so others know how to "call" the function

  5. 5 "Functional" Programming • While we can write arithmetic // Add 3 numbers expressions directly in C++, let's practice a = x + y + z; using functions to perform the same // which upholds the order of ops a = add(add(x,y),z); operations. a = add(x,add(y,z)); • Suppose you are given: // Exercise 1 – add(p, q) // returns p+q a = x / y + y * z – x; – sub(p, q) // returns p-q – mul(p, q) // returns p*q a = ________________________________ – div(p, q) // returns p/q // Exercise 2 • Convert the following expressions to use a = x * (y – z) / z; functions and no operators ( +,-,*,/ ) a = ________________________________ • Key Ideas: – Execution works from inside to outside (i.e. f(g(x)) invokes g(x) first) Disclaimer : These functions (add, sub, etc.) – The return value of a function is are fictitious and in C++ we just use the +, -, etc. operators, but this is to practice using substituted and used in the larger functions. expression

  6. 6 Function call statements #include <iostream> • Reminder that you can call a #include <cmath> #include <algorithm> using namespace std; function anywhere int main() • Result is replaced into bigger { // can call functions expression // in an assignment double res = cos(0); // res = 1.0 • Take care to "save" the result // can call functions in an – If you don't save the return value // expression sqrt(2) / 2; // forgot to save result into a variable or use it res = sqrt(2) / 2; // save 1.414/2 in res immediately, the result is lost cout << max(34, 56) << endl; // outputs 56 return 0; } http://www.cplusplus.com/reference/cmath/

  7. 7 User Defined Functions #include <iostream> using namespace std; • We can define our own int max(int a, int b); // prototype functions int main() { • Good practice is to "declare" int x, y, mx; cin >> x >> y; your function by placing the /* Code for main */ prototype (signature) at the top of your code } • "Define" the function (actual int max (int a, int b) { code implementation) if(a > b) return a; // immediately stops max anywhere by placing the code else return b; // immediately stops max in { } } • As shown it is defined but never used (no one actually "calls" the max function)

  8. 8 Calling a Function (1) #include <iostream> using namespace std; • We "call" or "invoke" the function by: int max(int a, int b); // prototype – Using its name and place variables or int main() constants that the current function { int x, y, mx; has declared in the order that we cin >> x >> y; want them to map to the /* Call the function */ parameter/argument list mx = max(x, y); – First variable listed (x) will map to the /* Bad */ first parameter (a) in the function's mx = int max(x, y); argument list, the second variable (y) mx = max(int x, int y); to the second parameter (b), etc. mx = max(a, b); max(x, y); • Don't – Relist the return type in the call } – Relist the type of the arguments int max (int a, int b) { – Use variable names that don't exist in if(a > b) return a; // immediately stops max the current function else – Forget to save the returned value return b; // immediately stops max }

  9. 9 Calling a Function (2) #include <iostream> using namespace std; • The we can "call" (activate/invoke) our function int max(int a, int b); // prototype from any other location in our code as many int main() times as we like { • Semantics of a function call: int x, y; cin >> x >> y; // User types: -5 7 – Pause the caller code (i.e. main) 7 – Pass copies of the arguments to the function (i.e. int mx = 1 + max (x, y); // call max pass a copy of x and y to a and b) cout << mx << endl; – Let the function execute 0 cout << max (0, x) << endl; // call max – When the function completes we return back to } the caller (i.e. main) and resume execution – int max (int a, int b) Any return value is substituted in place of the { function call if(a > b) • Notice 2 sets of parameter names: return a; // immediately stops max else – "Formal names": Generic parameter names used return b; // immediately stops max as placeholders to refer to an argument inside } the code (e.g. a title like "CEO" or "parent" that Program Output (if user types -5 7): refer to a specific person" – "Actual" names: True parameters that the 8 formals will reference (e.g. "Jeff Bezos", "Mark 0 Zuckerberg", etc.)

  10. 10 Execution Timeline #include <iostream> using namespace std; 1. We always start at main() and execute sequentially int max(int a, int b); // prototype until a function call or the end of main() int main() 2. When we hit a function call, execution of main { pauses and execution of max begins int x, y, mx; 1 cin >> x >> y; // User types: -5 7 3. Max will compare the arguments and return the 7 6 5 bigger int mx = 1 + max (x, y); // call max cout << mx << endl; 7 4. Upon return we go back to where we left off in the 0 previous function and replace the function call 2 cout << max (0, x) << endl; // call max with the return value } 8 5. We continue to evaluate the expression in which 10 int max (int a, int b) the function call was made (i.e. 1 + max) { 4 3 9 if(a > b) 6. We assign the result to mx return a; // immediately stops max 7. We continue sequentially until another function else return b; // immediately stops max call or until the end of main() } 8. Another function call again causes main to pause Program Output (if user types -5 7): and max begins execution anew 8 9. Max compares arguments 0 10. It then returns to the caller (main) and substitutes its return value in the larger expression

  11. 11 Example Functions 1 Function Signature/Prototype double calcInterest(double amt, int yrs, double rate); main #include <iostream> #include <cmath> using namespace std; 30 r amount // prototype double calcInterest (double amt, int yrs, double rate); int main() { double amount, r; cin >> amount >> r; double interest = calcInterest (amount, 30, r); amt yrs rate cout << "Interest: " << interest << endl; return 0; } interest calcInterest double calcInterest (double amt, int yrs, double rate) { return amt * pow(rate/12, 12*yrs); }

  12. 12 Example Functions 2 Function Signature/Prototype bool getAndCheckLogin(string exp_pwd); #include <iostream> main using namespace std; pass // prototype bool getAndCheckLogin (string exp_pwd); Open123! int main() { string pass = "Open123!"; // secret password bool valid; valid = getAndCheckLogin (pass); if( valid == true) { cout << "Success!" << endl; } exp_pwd else { cout << "Password mistmatch!" << endl; } return 0; getAndCheckLogin } valid bool getAndCheckLogin (string exp_pwd) { string pwd; cout << "Enter your password: " << endl; cin >> pwd; return pwd == exp_pwd; }

  13. 13 Example Functions 3 Function Signature/Prototype void printLoginResult(bool correct); #include <iostream> main using namespace std; // prototype valid void printLoginResult (bool correct); int main() { string pass = "Open123!"; // secret password bool valid; valid = getAndCheckLogin (pass); printLoginResult (valid); correct return 0; } printLoginResult void printLoginResult (bool correct) { if(correct == true) { cout << "Success!" << endl; } else { cout << "Password mistmatch!" << endl; } }

  14. 14 Example Functions 4 Function Signature/Prototype bool genCoinFlip(); #include <iostream> main #include <cstdlib> using namespace std; // prototype bool genCoinFlip (); int main() { bool heads; heads = genCoinFlip(); if(heads == true) { cout << "Heads!" << endl; } else { cout << "Tails!" << endl; } return 0; } heads genCoinFlip bool genCoinFlip () { int r = rand(); // Generate random integer return (r%2) == 1; }

Recommend


More recommend