c c functions
play

C/C++ Functions Mark Redekopp 2 A QUICK LOOK 3 Function - PowerPoint PPT Presentation

1 C/C++ Functions Mark Redekopp 2 A QUICK LOOK 3 Function Signatures/Prototypes Also called procedures or methods 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


  1. 1 C/C++ Functions Mark Redekopp

  2. 2 A QUICK LOOK

  3. 3 Function Signatures/Prototypes • Also called procedures or methods • 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

  4. 4 User Defined Functions #include <iostream> • using namespace std; We can define our own functions // prototype / declaratoin • Good practice is to "declare" your int max(int a, int b); function by placing the prototype int main() (signature) at the top of your code { int x, y, mx; • "Define" the function (actual code cin >> x >> y; implementation) anywhere by /* Code for main */ placing the code in { } • As shown it is defined but never used (no one actually "calls" the } max function) // Definition int max (int a, int b) { • At most 1 return value if(a > b) – void = 0 return values return a; // immediately stops max else • Return value is substituted at the return b; // immediately stops max site of the function call and used in } the larger expression

  5. 5 Execution of a Function #include <iostream> • using namespace std; Statements in a function are executed // prototype / declaratoin sequentially by default int max(int a, int b); • Defined once, called over and over int main() • Functions can call other functions { int x, y, mx; – Goes and executes that collection of code cin >> x >> y; // say "6 103" then returns to continue the current function /* Code for main */ • Compute max of two integers 6 z = max(x,4); Each call causes the program to pause the cout << z << endl; current function, go to the called function 103 cout << max(x, y) << endl; and execute its code with the given return 0; arguments then return to where the calling } function left off, • Return value is substituted in place of the // Definition int max (int a, int b) function call { if(a > b) return a; else return b; }

  6. 6 Anatomy of a function void printMenu() • Return type (any valid C type) { cout << “Welcome to ABC 2.0:” << endl; cout << “===================" << endl; – void, int, double, char, etc. cout << “ Enter an option:" << endl; cout << “ 1.) Start" << endl; – void means return nothing cout << “ 2.) Continue" << endl; cout << “ 3.) End \n" << endl; • Function name } bool only_2_3_factors(int num) – Any valid identifier { while(num % 2 == 0){ • Input arguments inside () ... } – Act like a locally declared ... if(num==1) variable return 1; return 0; • Code } – In {…} double triangle_area(double b, double h) { • Non-void functions must have double area = 0.5 * b * h; return area; 1 or more return statements } – First 'return' executed immediately quits function

  7. 7 Parameter Passing • Formal parameters, a and b #include <iostream> using namespace std; – Type of data they expect int max(int a, int b) Formals – Names that will be used internal to the function to { refer to the values (placeholders/aliases) for if(a > b) actuals return a; else • Actual parameters return b; – Actual values input to the function by the caller } – A copy is made and given to function int main() x { int x=6, z; Actuals 6 4 Actuals z = max(x,4); cout << “Max is “ << z << endl; Actuals z = max(125, 199); Formals a b 6 cout << “Max is “ << z << endl; return 0; max() } return val Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

  8. 8 Parameter Passing #include <iostream> • Formal parameters, n1 and n2 using namespace std; – Type of data they expect double avg(int n1, int n2) { – Names that will be used internal to the function to double sum = n1 + n2; refer to the values return sum/2.0; • Actual parameters } copy copy – Actual values input to the function code by the int main() caller { – A copy is made and given to function int x=6, y = 9; double z; x y z = avg(x,y); Actuals 6 9 cout << “AVG is “ << z << endl; z = avg(x, 2); cout << “AVG is “ << z << endl; Formals n1 n2 7.5 return 0; } avg() return val Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

  9. 9 Parameter Passing #include <iostream> • Formal parameters, n1 and n2 using namespace std; – Type of data they expect void inc(int x) { – Names that will be used internal to the function to x = x+1; refer to the values } • Actual parameters – Actual values input to the function code by the int main( ) caller { – A copy is made and given to function int x=6; x inc(x); 6 cout << “X is “ << x << endl; Actuals 6 return 0; } Formals x inc() x 7 Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

  10. 10 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); }

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

  12. 12 Example Functions 3 Function Signature/Prototype void validateLogin(string exp_pwd); #include <iostream> main using namespace std; // prototype pass void validateLogin (string exp_pwd); int main() { string pass = "Open123!"; // secret password bool valid; cout << "Enter your password: " << endl; validateLogin(pass); exp_pwd return 0; } checkLogin void validateLogin (string exp_pwd) { string actual; cin >> actual; if(actual == exp_pwd){ cout << "Success!" << endl; } else { cout << "Incorrect!" << endl; } }

  13. 13 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; }

  14. 14 Program Decomposition • C is a procedural language – Main unit of code organization, problem decomposition, and abstraction is the “function” or “procedure” – Function or procedure is a unit of code that • Can be called from other locations in the program • Can be passed variable inputs (a.k.a. arguments or parameters) • Can return a value to the code that called it • C++ is considered an “object - oriented” language (really just adds objected-oriented constructs to C) – Main unit of organization, problem decomposition, and abstraction is an object (collection of code & associated data)

  15. 15 Exercise • To decompose a program into functions, try listing the verbs or tasks that are performed to solve the problem – Model a card game as a series of tasks/procedures… • shuffle(), deal(), cut(), drawCard(), checkIfWon (), … – A database representing a social network • addUser(), addFriend(), updateStatus(), etc.

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend