<<

Functions Spring 2005

Outline User-defined Functions • Writing and calling a function – Header and body – Function Larry Caretto – Passing information to a function Computer Science 106 – Returning values in the function name Computing in Engineering and Science • void functions with no return value • Use pass-by-reference to change Spring 2005 variables in the calling program • Variable and global variables

2

Introduction to Functions Why do we write functions? • functions like pow, atan and • First use of functions was for code like sqrt used previously mathematical function calculations • Statement to set x = yz3: – Specialized calculation done repeatedly – x = y * pow( z, 3 ); – Want to write code only one time – Note order of arguments important; the call – Want to be able to pass values of pow( 3, z ) gives 3z parameters to code and get value back – Use #include for this function • As programs got more complex, • You can write your own functions breaking code into functions provided a – Why do we write functions? way to organize complex code – How do we write code for functions?

3 4

How do we write functions? Operation of Functions • ++ code is a collection of functions • Any function (the caller) can call another • Each function, including main, has the function by using the name of the same level of importance function being called in an expression – Close code for each function before • The statement calling the function starting a new function sends information from the caller int main() { // body of main • Execution control is transferred to the } function being called int myFunction( …… ) { // body of myFunction • The function being called returns control } and (usually) results to the caller

5 6

1 Functions Spring 2005

Operation of Functions Writing and Using Functions • The function being called uses the • Organize the program into individual information it receives to do a set of functions that are called by main calculations or procedures – Simple example: main calls three functions: (1) input function, (2) calculation • In the usual case, the function being function and (3) output funciton called returns a result to the caller in the • Write code for each function (and main) location of the function name – Write function header to specify • Example: = pow(b,2) – 4 * a * c; information received from calling function – calls the pow function with values of b and 2 – Write function body to calculate results and return them to “calling” function – and the result b2 is returned in function name, pow, for further use in an expression • Write function calls to exchange data 7 8

Writing and Using Functions II Function • Library functions, such as pow(x, y) to • Each function has a header and a body compute xy, transfer information based – Header specifies on the order of the variables • Name of function • Type of value returned by the function name • This is true for user-defined functions as • List of variables in the function whose values well are determined by the calling program – Information transferred from a list of – Body gives code executed by the function variables in the calling function to a list of • Function at start of code variables in the function called provide information to – Correspondence based on order of – Same as header except a semicolon is variables in function header and statement added at the end calling the function – Can omit variable names 9 10

Function Basics II Function Header • Example of header and body • Header has following syntax: double myPow ( double number, – ( ) double power ) // header – specifies the type of value returned by the function { – is the name you choose for your // Body,in braces contains function; this name is used to call the function from another function // actual code for function – specifies type and } names of variables in function whose values come from the calling program • Header defines information that will be – There is no semicolon in the function received from calling function header

11 12

2 Functions Spring 2005

Function Header II Argument List • Example of function, myPow, a user- • Example on previous chart had two defined function to replace pow parameters in argument list – Pass the number and the power to the – ( ) function as type double – double myPow ( double number, – Return the result as type double double power ) – General header syntax from previous chart • Function will use number and power as ( ) type double variables – double myPow ( double number, • Values for these variables set by other double power ) function that calls (uses) myPow

13 14

Passing arguments The • Based on order of arguments in function • We have used this statement in main as header and in calling statement return EXIT_SUCCESS; • Recall the library pow function was • The general syntax of this statement is called as pow(number, power) return ; – pow(3,4) = 34 but pow(4,3) = 43 • may be a constant, a – What is result of following code variable or an expression double number = 3, power = 4; • This is value returned to calling program cout << pow( power, number) in function name Result is 43; only the order counts! • return always transfers control

15 16

Organization of Function Code Alternative Function Code

double myPow( double number, double myPow( double number, double power ) double power ) { { double result = exp( power * return = exp( power * log( number ) ); log( number ) ); return result; } } • Can use following prototype without • Place following prototype at top of code variable names at top of code double myPow( double number, double myPow( double, double ); double power );

17 18

3 Functions Spring 2005

Another function Example Use of bool leap( int year ) bool leap ( int year );// prototype bool leap( int year ) Header int main() // examples of use Type { { cout << “Enter a year: “; if ( year % 4 != 0 ) int y; cin >> y; Name return false; bool cond = leap( y ); else if ( year % 400 == 0 ) return true; if ( leap( y ) ) {…} Argu- else if ( year % 100 == 0 ) if ( leap( y ) && month == 2 ) {…} ment return false; return EXIT_SUCCESS List Body else Multiple } return true; returns // leap and other functions go here }

19 20

Exercise Exercise • Write a function that takes two type int • Write a function that takes two type arguments and returns their difference double arguments and returns their quotient • Use this function to compute 3 – 5 • Use this function to compute 5/3 • Write the prototype • Write the prototype int diff( int a, int b) double div( double a, double b) { return a – b } { return a / b } //use: cout << diff( 3, 5 ); //use: cout << div( 5, 3 ); // prototype: int diff( int a, int b); // prototype: double div(double a, double b); 21 22

void functions with no return The return Statement • The type void used for functions that do • The return statement returns control not return a value and a value to the calling program – Functions, other than void functions use • Example: error message function the syntax return to return a void printError( int code ) value to the calling function in the function { name if ( code == 1) – Void functions may have a simple return cout << “Type one error\n”; statement without a value to return control else if ( code == 2 ) to the calling program at some point before cout << “Error two is … the end of the function else if // additional code • Functions may have more than one } // no return needed here return statement – return transfers control immediately

23 24

4 Functions Spring 2005

Empty Argument List Kinetic Energy Function • If a function does not need any values • Write a function that takes two type from the calling program an empty set double parameters, mass and velocity of parentheses is required and computes kinetic energy = mV2/2 • Example is function with several output double KE( double m, double V ) statements to describe purpose of code { void describeCode() return m * V * V / 2; { } cout << “This code ….. • Possible calls to this function cout << “Still more output totalE = KE( 4, 3 ) + PE; // No return needed for type void • What is result of this call } result = 50 + KE( 5, 2 ); 2 25 50 + 5 * 2 / 2 = 60 26

Kinetic Energy Function II Data Validation Function

double KE( double m, double V ) • The function getValidInt( int xMin, { int xMax,string name ) does the return m * V * V / 2; following tasks } – Prompts the user for an input variable • What is output from these calls? (named in the string passed in the third parameter) within a range defined by the double mass = 5, velocity = 2; 10 cout << KE( velocity, mass ); first and second parameters double e = PE + KE( 2*pow( velocity, – Gets the input from the user 2), velocity); – Tells the user if there is an error and gets double total = KE( mass * velocity, new input from the user in this case e = KE(2*22,2) = KE(8,2)=8*22/2 = 16 mass ); – Returns valid input to the calling function

total = KE(5*2,5) = KE(10,5)=10*52/2 = 12527 28

Data Validation Function II int getValidInt( int xMin, int xMax, string name ) • The function getValidInt described { on the previous chart is used in exercise // Function used to input integer seven and project one // data within a stated range • Examples of its use // Example function call to input a // value for a variable named int month = getValidInt( 1, 12, “month”); // hour with range between 0 and 23: // int hour = int mayDay = getValidInt( 1, 31, “day of the month” ); // getValidInt( 0, 23, “hour” ); int year = getValidInt( 1901, 2000, “year in the 20th century” ); int x; // Input data value bool badData; // Bad data flag // continued on next chart 29

5 Functions Spring 2005

do // Loop until user data in range if ( badData ) { // print error message cout << "Enter a value for " << name { << " between " << xMin << " and " cout << "\n\nIncorrect data; you " << xMax << ": "; << "entered " << name cin >> x; badData = x < xMin || x > xMax; << " = “ << x << "\n" if ( badData ) << name << "must be between " // error message code on next chart << xMin << " and " << xMax } << " Reenter the data now.\n"; while ( badData ); }

} // end of function

getValidInt Screen Results Program Structure Example • Call to getValidInt • Next chart: example for getValidInt int mayDay = getValidInt( 1, 31, “day of the month”); • before program that • Screen prompt showing parameters and uses function user input • In this example main calls function Enter a value for day of the month • Complete code for main is written start between 1 and 31: 0 of code for function Incorrect data; you entered day of the month = 0. day of the month must be • A call to the function transfers control to between 1 and 31. Reenter the data now. function with values in the function Enter a value for day of the month header variables from the caller between 1 and 31: 1 • Function returns value to main

33 34

int getValidInt( int, int, string); // prototype above Passing Information to Functions int main() { • Parameters in function header: formal int month = getValidInt( 1, 12, parameters or dummy parameters (also “month” ); called formal or dummy arguments) ……………… // other code return EXIT_SUCCESS • Values sent to function by calling } program: actual parameters or actual int getValidInt( int xMin, int xMax, arguments string name ) { int x; • Pass by value is default : when ……………………………… // other code a function is called a copy of the value cin >> x; of the argument is passed to the ……………………………… // other code function return x;

} 36

6 Functions Spring 2005

More on Information to Functions Pass-by-Value Example • In pass-by-value, the values of the //calling program actual arguments in the calling program double x = 10, y = 2; are not changed cout << “fake = “ << fake( x, y ); • The alternative to pass by value is pass cout << “, x = “ << “, y = “ << y; by reference // what is printed? – The memory address of the actual //function parameter is passed to the function double fake( double x, double y ) – Changes to the dummy parameter in the { function change the actual parameter in x +=10; y *= x; return 3 * y; the calling program }

37 38

Pass-by-value Operation Pass-by-reference • The code on the previous chart does • To use pass by reference place an not change the x and y values in the ampersand (&) between the type and calling program the parameter name in the function • Only values of x and y from the calling header: int f1( int& x, int& y ) program are passed to the function – Not a preferred programming style • Functions cannot changed values of – Used only when we have to change more variables that are passed by value than one parameter (e.g., input routine, vector components, etc.) • How do we use pass by reference to – Exercise seven uses an input function change the values of parameters which must have pass by reference passed into a function?

39 40

Pass-by-reference II Pass-by-Value Example • Default is pass-by-value where changes //calling program segment to parameters do not affect variables in double u = 5, v = 2; the calling program cout << “fake = “ << fake( u, v ); double fake1 ( int x, double y ) cout << “\nu =“ << u << “, v =“ << v; { x++; y += x; return x * y; } // what is printed? fake = 90 • Ampersand (&) gives pass by reference //function u = 5, v = 2 that changes program variables double fake( double x, double y ) double fake2 ( int& x, double& y ) { { x++; y += x; return x * y; } x +=10; y *= x; return 3 * y; } x = 5 + y = 2 * fake( u, v ) = 41 10 = 15 15 = 30 3 * 30 = 90 42

7 Functions Spring 2005

Pass-by-Reference Example Pass-by-Reference Example II

//calling program segment double u = 3, v = 4; double u = 3, v = 4; cout << “fake = “ fake( u, v ); cout << “fake = “ fake( u, v ); cout << “\nu =“ << u << “, v =“ << v; cout << “\nu =“ << u << “, v =“ << v; double fake( double& x, double& y ) // what is printed? fake = 156 { x +=10; y *= x; return 3 * y; } //function u = 13, v = 52 // at start fake has x = 3, y = 4 double fake(double& x, double& y ) // fake code sets x = x + 10 = 13 { // and y = y * x = 4 * 13 = 52 x +=10; y *= x; return 3 * y; // fake returns 3 * 52 = 156 and } x = 3 + y = 13 * fake( u, v ) = // changes u to 13 and v to 52 10 = 13 4 = 52 3 * 52 = 156 43 44

Example: Converting Vectors Converting Vectors II

• Convert different y • Write two functions to convert between representations of two- the two different representations dimensional vectors – Polar to rectangular function has Fy – Polar: magnitude, |F| and |F| magnitude and direction as inputs and direction, θ θ x returns x-component and y-component – Rectangular to polar function has x- F – Rectangular: components, Fx, x component and y-component as inputs and and Fy, along the x and y axes returns magnitude and direction -1 • Conversion equations – Use atan2 function for θ = tan (Fy / Fx ) to 2 2 1/2 -1 –|F| = (Fx + Fy ) , θ = tan (Fy / Fx ) get full 2π result (-π/2 < atan result < π/2) –Fx = |F|cos θ,Fy = |F|sin θ,

45 46

Converting Vectors III Converting Vectors IV • Each function has two input values and void polarToRectangular ( computes two results double magnitude, double angle, • Use pass by reference to get results double& xComponent, back to calling program double& yComponent ) { • Inputs to function are pass by value xComponent = magnitude • Function type can be void since function * cos( angle ); name need not return a value yComponent = magnitude – Functions using pass by reference to * sin( angle ); return values sometimes return an error } code in the function name

47 48

8 Functions Spring 2005

Converting Vectors V Use of Conversion Functions

void rectangularToPolar ( const double PI = 4 * atan(1); double xComponent, double x = 3, y = 4; double yComponent, double A, theta; double& magnitude, double& angle ) rectangularToPolar(x, y, A, theta ); { cout << x << “ “ << y << “ “ magnitude = sqrt( << A << “ “ << theta << endl; pow( xComponent, 2 ) + double size = 10, direction = PI / 8; pow( yComponent, 2 ) ); double xComp, yComp; angle = atan2 ( yComponent, polarToRectangular( size, direction, xComp, yComp ); xComponent ); cout << size << “ “ << direction << } “ “ << xComp << “ “ << yComp; 49 50

Pass-by-Reference Exercise Pass-by-Reference Exercise • Write an input function that prompts the void input( double& x, double& y) user to enter two type double variables, x { and y, and returns these values to the cout << “Enter x and y: “; calling program cin >> x >> y } void input( double& x, double& y) { • Write the prototype for this function and a call to the function to get x and y cout << “Enter x and y: “; void input( double& x, double& y ); cin >> x >> y; double x, y; } input ( x, y ); Optional 51 52

Use of Pass by Reference Scope of a Variable

• Calling programs use same approach for • Scope of a variable is the part of program that can use the variable pass by reference and pass by value • We see that we can have the same • Variable or expression is placed as one variable name in different functions of the arguments to the function • These names, although the same, • Do not use a constant in a function call occupy two different memory locations unless it is passed by value in the computer and are not related • Data types (and ampersands for pass by • Even within a single function we can reference) are not used in function call limit the part of a function in which a variable is in scope (exists)

53 54

9 Functions Spring 2005

Background Basic Rule for Scope • All variables must be declared (given a • A variable defined in a set of braces type) before they are used only exists within those braces • Variables can be declared given a value • It can be used anywhere in the program when declared or later in the code below its initial declaration • Usually assign a value before first use – This includes sets of braces that are • Scope refers only to declaring a opened below the initial declaration variable, not to assigning it a value • After close of brace where variable is – This is just a reminder that we have to initialize variables as well as declare them declared, the variables “goes out of scope” it cannot be used

55 56

Example of Scope Another example of Scope double x; double y = 0, c = 4; if ( c == 4 ) if ( c == 4 ) { { x = 12; double y = 2; // different var- double y = 2; // limited scope // iable with limited scope } } cout << x << “ “ << y; cout << “y = “ << y; // statement above will give syntax // statement above will print y = 0 // error; y is not defined here // from initial declaration of y

57 58

Where to Declare Variables Another Example

• Current programming practice declares • Code below will not work because yesNo variables as close to first time of use as goes out of scope after closing brace possible do • May have to be declared earlier in the { // program code code to give appropriate scope cout << “Another run(Y/N)? “; – First use of variable may be inside a loop char yesNo; // bad location – We must declare it prior to the loop if we cin >> yesNo; want to use if following the loop } while( yesNo == ‘Y’ || yesNo == ‘y’ );

59 60

10 Functions Spring 2005

Another Example Corrected Global Variables

• Code below works because yesNo is • Global variables have scope of more than one function declared before brace opening the loop – Declared outside function boundaries char yesNo; // correct location – Have scope of all functions from do declaration to end of file { // program code – Usually declared at top of program to be cout << “Another run(Y/N)? “; present in all functions cin >> yesNo; – Considered bad programming practice – Use only when variable must be accessed } by several functions or there are problems while( yesNo == ‘Y’ || yesNo == ‘y’ ); in passing the variable

61 62

Trace Global Variables Project Two Global Variables • What is program output? • In project two the main function calls a int status = 0; // global function which calls a third function int main() { • We want to get data from main to the cout << status << “ “; third function f1(); f2(); • We do not want to rewrite the second cout << “ “ << status // more function, but it does not allow us to pass } the necessary information void f1() { status = 1; } • Use global variables to get the void f2() {cout << status << endl;} information from main to third function • Program output is 0 1 1

63 64

Summary Summary Continued • Use functions to organize code • Pass information to function through • Elements of a function argument list in function header – Header with type, name, and argument list – Correspondence by position of arguments in header and position of arguments in – Body with code that function executes calling function – Statement to return information through – Default of pass by value will not change function name in calling program must be arguments in calling function included in function body – Pass by reference (requires ampersand(&) – Prototype at start of program which is in function header and prototype) changes header with a semicolon arguments in calling function • Function name calls function and returns value 65 66

11 Functions Spring 2005

Summary Concluded Review Function Introduction • Scope of variables is part of program • A C++ program is a collection of where a variable can be used functions • Variables can only be used within – Each function is written as a unit braces where there are declared and – Complete code for one function before only following the declaration starting to write a new one • Global variables, declared outside any – Execution starts in main function function, can be used by any function • Upon calls to a function, information and following the declaration control is transferred to the function • Value returned in function name

67 68

Information Transfer • Function header has argument list • Variables in that list (called dummy parameters or dummy arguments) are determined by call to function • Call to function has actual arguments or actual parameters in same order that dummy arguments appear – Order is all that matters in transferring information to a function

69

12