Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 4 Functions.

Slides:



Advertisements
Similar presentations
Copyright © 2003 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1 Created by David Mann, North Idaho College.
User Defined Functions
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 5 Functions for All Subtasks.
1 Walter Savitch Chapter 3 Procedural Abstraction and Functions That Return a Value Slides by David B Teague, Western Carolina University, A constituent.
Functions  Programmer-Defined Functions  Local Variables in Functions  Overloading Function Names  void Functions,  Call-By-Reference Parameters in.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1 ; Programmer-Defined Functions Two components of a function definition.
Chapter 3 Function Basics Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Functions.
CS 201 Functions Debzani Deb.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Copyrights ©2005 Pearson Addison-Wesley. All rights reserved. 1 Chapter 4 Procedural Abstraction and Functions That Return a Value.
CSC 200 Lecture 04 2/8/06 Matt Kayala. Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
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 4 Procedural Abstraction and Functions That Return a Value.
Function. Introduction Library function New defined function Random number generator Scope Inline function Function overload Function Function.
Chapter 6: User-Defined Functions I Instructor: Mohammad Mojaddam
Lecture 9m: Top-Down Design with Functions COS120 Software Development Using C++ AUBG, COS dept.
Lecture 3 Using C++ Functions COSC1567 C++ Programming.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
Chapter 3 Procedural Abstraction and Functions That Return a Value.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
C++ Programming: Basic Elements of C++.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Procedural Abstraction and Functions That Return a Value.
Functions in C Programming Dr. Ahmed Telba. If else // if #include using namespace std; int main() { unsigned short dnum ; cout
Slide 1 Chapter 3 Function Basics. Slide 2 Learning Objectives  Predefined Functions  Those that return a value and those that don’t  Programmer-defined.
Today’s Lecture Predefined Functions. Introduction to Functions  Reuse Issue  Building Blocks of Programs  Two types of functions  Predefined  Programmer.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Top-Down Design SLO1.8 Explain the benefits of dividing large programming tasks to smaller.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
CPS120: Introduction to Computer Science Functions.
Functions. Let’s look at the 2 programs of evaluating: y=2^3+2^5+2^6; #include using namespace std; int main() { int y=0; int partResult=1; for (int i=1;
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
Copyright © 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Modular Programming ELEC 206 Computer Applications for Electrical Engineers Dr. Ron Hayne.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 6: User-Defined Functions I.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 6: User-Defined Functions I.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Copyright © 2015 Pearson Education, Ltd.. All rights reserved. Chapter 4 Procedural Abstraction and Functions That Return a Value.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.
Functions and Libraries. The idea of a function Functions in programming A function is a block of code that has been given a name. To invoke that code.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
Chapter 6: User-Defined Functions I
Procedural Abstraction and Functions That Return a Value
Procedural Abstraction and Functions That Return a Value
Procedural Abstraction and Functions That Return a Value
Predefined Functions Revisited
TMF1414 Introduction to Programming
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists Function Basics TBC=15 Dr. Xiao Qin.
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
CMPT 201 Functions.
User-Defined Functions
Functions Review Programmer-Defined Functions
Chapter 6: User-Defined Functions I
Predefined Functions Revisited
CS 144 Advanced C++ Programming January 31 Class Meeting
Chapter 4 Procedural Abstraction and Functions That Return a Value 1
Presentation transcript:

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 4 Functions

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 4.1 Top-Down Design 4.2 Predefined Functions 4.3 Programmer-Defined Functions 4.4 Procedural Abstraction 4.5 Local Variables 4.6 Overloading Function Names Slide 4- 3

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Top Down Design To write a program Develop the algorithm that the program will use Translate the algorithm into the programming language Top Down Design (also called stepwise refinement) Break the algorithm into subtasks Break each subtask into smaller subtasks Eventually the smaller subtasks are trivial to implement in the programming language Slide 4- 4

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Benefits of Top Down Design Subtasks, or functions in C++, make programs Easier to understand Easier to change Easier to write Easier to test Easier to debug Easier for teams to develop Slide 4- 5

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Predefined Functions C++ comes with libraries of predefined functions Example: sqrt function the_root = sqrt(9.0); returns, or computes, the square root of a number The number, 9, is called the argument the_root will contain 3.0 Slide 4- 6

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Calls Slide 4- 7 sin(x)Sine of an angle x (measured in radians) cos(x) Cosine of an angle x (measured in radians) tan(x) Tangent of an angle x (measured in radians) asin(x)Sin-1 (x) where x (measured in radians) acos(x)Cos-1 (x) where x (measured in radians) exp(x)Exponential function of x (ex) log(x)logarithm of x log 10(x)Logarithm of number x to the base 10 sqrt(x)Square root of x pow(x, y)x raised to the power y abs(x)Absolute value of integer number x fabs(x)Absolute value of real number x

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Example #include using namespace std; int main() { double x,y; cout << " Enter the value of x "; cin >> x; if (x >= 0 ) y= x*x + sqrt(x); else if ( x > -10 && x < 0 ) y= 1 - exp (x); else y= fabs ( x + 5 ); cout << " y = " <<y<<endl; return 0; } Slide 4- 8

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Other Predefined Functions Slide 4- 9

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Random Number Generation Really pseudo-random numbers 1. Seed the random number generator only once #include srand(time(0)); 2. The rand() function returns a random integer that is greater than or equal to 0 and less than RAND_MAX rand(); Slide 1- 10

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Random Numbers Use % and + to scale to the number range you want For example to get a random number from 1-6 to simulate rolling a six-sided die: int die = (rand() % 6) + 1; Can you simulate rolling two dice? Generating a random number x where 10 < x < 21? Slide 1- 11

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Type Casting Recall the problem with integer division: int a(10),b(3); double pi = static_cast (a)/b; A Type Cast produces a value of one type from another type This would not! int a(10),b(3); double pi = static_cast (a/b); Slide 4- 12

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Old Style Type Cast C++ is an evolving language This older method of type casting may be discontinued in future versions of C++ candy_per_person = double(total_candy)/number_of_people; Slide 4- 13

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Section 4.2 Conclusion Slide Can you Determine the value of d? double d = 11 / 2; Determine the value of pow(2,3)fabs(-3.5)sqrt(pow(3,2)) 7 / abs(-2)ceil(5.8)floor(5.8) Convert the following to C++

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 4.3 Programmer-Defined Functions

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Programmer-Defined Functions Two components of a function definition Function declaration (or function prototype) Shows how the function is called Must appear in the code before the function can be called Syntax: Type_returned Function_Name(Parameter_List); //Comment describing what function does Function definition Describes how the function does its task Can appear before or after the function is called Syntax: Type_returned Function_Name(Parameter_List) { //code to make the function work } Slide ;

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Example // function example #include using namespace std; int addition (int a, int b) { int r; r=a+b; return (r); } int main () { int z; z = addition (5,3); cout << "The result is " << z; return 0; } Slide 4- 17

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Scope of variables Slide 4- 18

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Example 2 // function example #include using namespace std; int subtraction (int a, int b) { int r; r=a-b; return (r); } int main () { int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) << '\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; } Slide 4- 19

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Functions of void (No type) // void function example #include using namespace std; void printmessage () { cout << "I'm a function!"; } int main () { printmessage (); return 0; } Slide void printmessage (void) { cout << "I'm a function!"; } printmessage (); printmessage;

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Alternate Declarations Two forms for function declarations List formal parameter names List types of formal parmeters, but not names Examples: double total_cost(int number_par, double price_par); double total_cost(int, double); Function headers must always list formal parameter names! Slide 4- 21

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Order of Arguments Compiler checks that the types of the arguments are correct and in the correct sequence. Compiler cannot check that arguments are in the correct logical order Example: Given the function declaration: char grade(int received_par, int min_score_par); int received = 95, min_score = 60; cout << grade( min_score, received); Produces a faulty result because the arguments are not in the correct logical order. The compiler will not catch this! Slide Display 4.5 (1) Display 4.5 (2)

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Definition Syntax Slide 4- 23

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Function Definition Syntax Within a function definition Variables must be declared before they are used Variables are typically declared before the executable statements begin At least one return statement must end the function Each branch of an if-else statement might have its own return statement Slide 4- 24

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. bool Return Values A function can return a bool value Such a function can be used where a boolean expression is expected Makes programs easier to read if (((rate >=10) && ( rate < 20)) || (rate == 0)) is easier to read as if (appropriate (rate)) If function appropriate returns a bool value based on the the expression above bool appropriate(int rate) { return (((rate >=10) && ( rate < 20)) || (rate == 0)); } Slide 3- 25

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 4.5 Local Variables

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Constants and Global Variables Literals : int a = 5; Defined constants (#define): #define PI Declared constants (const) const int a= 100; Global Constant Available to any function, and declared outside any function body Example: const double PI = ; double volume(double); int main() {…} PI is available to the main function and to function volume Slide 4- 27

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Formal Parameters are Local Variables Slide //Formal Parameter Used as a Local Variable //Law office billing program. #include using namespace std; const double RATE = ; //Dollars per quarter hour. double fee(int hours_worked, int minutes_worked); int main( ) { int hours, minutes; double bill; cout << "Enter the hours and minutes:\n"; cin >> hours >> minutes; bill = fee(hours, minutes); cout << "For " << hours << " hours and " << minutes << " minutes, your bill is $" << bill << endl; return 0; } double fee(int hours_worked, int minutes_worked) { int quarter_hours; minutes_worked = hours_worked*60 + minutes_worked; quarter_hours = minutes_worked/15; return (quarter_hours*RATE); }

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Example: Factorial n! Represents the factorial function n! = 1 x 2 x 3 x … x n Requires one argument of type int, n Returns a value of type int Uses a local variable to store the current product Decrements n each time it does another multiplication n * n-1 * n-2 * … * 1 Slide 4- 29

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Example: Factorial Slide //DISPLAY 4.16 Factorial Function //Function Declaration #include using namespace std; int factorial(int n); int main () { for (int i(1); i<=10; i++) cout << factorial(i) << endl; return 0; } int factorial(int n) { int product = 1; while (n > 0) { product = n * product; n--; } return product; }

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 4.6 Overloading Function Names

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overloading Examples double ave(double n1, double n2) { return ((n1 + n2) / 2); } double ave(double n1, double n2, double n3) { return (( n1 + n2 + n3) / 3); } Compiler checks the number and types of arguments in the function call to decide which function to use cout << ave( 10, 20, 30); uses the second definition Slide 4- 32

Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Automatic Type Conversion Given the definition double mpg(double miles, double gallons) { return (miles / gallons); } what will happen if mpg is called in this way? cout << mpg(45, 2) << “ miles per gallon”; The values of the arguments will automatically be converted to type double (45.0 and 2.0) Slide 4- 33