Você está na página 1de 46

Functions Functions with Arrays

Divide

and conquer

Construct a program from smaller pieces or components Each piece more manageable than the original program

Modules:

functions Programs use new and prepackaged modules


New: programmer-defined functions Prepackaged: from the standard library

Functions

invoked by function call

Function name and information (arguments) it needs

Function

definitions

Only written once

Perform

common mathematical calculations


called by writing

Include the header file <cmath>

Functions

functionName (argument); or functionName(argument1, argument2, );


Example

cout << sqrt( 900.0 );


sqrt (square root) function The preceding statement would print 30.0 All functions in math library return a double
4

Function

arguments can be

Constants
sqrt( 4 );

Variables

sqrt( x );
sqrt( sqrt( x ) ) ; sqrt( 3 6 * x );

Expressions

De sc rip tio n Exa m p le rounds x to the smallest integer ceil( 9.2 ) is 10.0 not less than x ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0 (x in radians) exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) rounds x to the largest integer floor( 9.2 ) is 9.0 not greater than x floor( -9.8 ) is -10.0 fmod( x, y ) remainder of x/y as a floating- fmod( 13.657, 2.333 ) is 1.992 point number log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3 sin( x ) trigonometric sine of x sin( 0.0 ) is 0 (x in radians) sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x tan( 0.0 ) is 0 (x in radians) Fig . 3.2 M a th lib ra ry func tio ns.
6

M e tho d ceil( x )

Functions

Modularize a program Software reusability

Call function multiple times

Local

variables

Known only in the function in which they are defined All variables declared in function definitions are local variables Local variables passed to function when called Provide outside information
7

Parameters

Function

prototype

Tells compiler argument type and return type of function int square( int );

Function takes an int and returns an int

Explained in more detail later

Calling/invoking square(x);

a function

Parentheses an operator used to call function


Pass argument x Function gets its own copy of arguments

After finished, passes back result


8

Format

for function definition

return-value-type function-name( parameterlist ) { declarations and statements } Parameter list

Comma separated list of arguments Data type needed for each argument If no arguments, use void or leave blank Data type of result returned (use void if nothing returned)

Return-value-type

Example function
int square( int y ) { return y * y; }

return keyword

Returns data, and control goes to functions caller

If no data to return, use return;

Function ends when reaches right brace

Control goes to caller

Functions cannot be defined inside other functions Next: program examples

10

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 1

// code 1 // Creating and using a programmer-defined function. #include <iostream> using std::cout; using std::endl; int square( int );

Function prototype: specifies data types of arguments and return // function prototype values. square expects an int, and returns an int. Parentheses () cause function to be called. When done, it returns the result.

int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call

cout << endl;

Definition of square. y is a copy of the argument passed. Returns y * y, or y } // end main squared. // square function definition returns square of an integer
return 0; // indicates successful termination int square( int y ) // y is a copy of argument to function { return y * y; // returns square of y as an int } // end function square 4 9 16 25 36 49 64 81 100

11

1 2 3

// Finding the maximum of three floating-point numbers. #include <iostream> using std::cout;

4 using std::cin; 5 using std::endl; 6 7 double maximum( double, double, double ); // function prototype 8 9 int main() 10 { 11 double number1; 12 double number2; 13 double number3; 14 15 cout << "Enter three floating-point numbers: "; 16 cin >> number1 >> number2 >> number3; 17 // number1, number2 and number3 are arguments to 18 // the maximum function call 19 cout << "Maximum is: " 20 << maximum( number1, number2, number3 ) << endl;
21 return 0; // indicates successful termination 22 } 23// function maximum definition; 24 // x, y and z are parameters

Function maximum takes 3 arguments (all double) and returns a double.

Comma separated list for multiple parameters.


Enter three floating-point numbers: 99.32 37.3 27.1928 Maximum is: 99.32 Enter three floating-point numbers: 1.1 3.333 2.22 Maximum is: 3.333 Enter three floating-point numbers: 27.9 14.31 88.99 12 Maximum is: 88.99

25 26 27 28 29 30 31 32

double maximum( double x, double y, double z ) { double max = x; // assume x is largest if ( y > max ) // if y is larger, max = y; // assign y to max if ( z > max ) // if z is larger, max = z; // assign z to max return max; } // max is largest value

Write

a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation.

Net Price = original Price - (original Price * discountRate / 100)

Such

a function could look like this:

double CalculateNetPrice(double discountRate) { double OrigPrice; }


1-13

double CalculateNetPrice(double discountRate) { double OrigPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); }

int main() { double finalPrice; double discount = 15; // That is 25% = 25


finalPrice = CalculateNetPrice(discount); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }

To

give a default value to an argument, when declaring the function, type the name of the argument followed by the assignment operator =, followed by the default value. The CalculateNetPrice() function, with a default value, could be defined as:

#include <iostream> using namespace std; double CalculateNetPrice(double discountRate = 25) { double origPrice;

cout << "Please enter the original price: "; cin >> origPrice;
return origPrice - (origPrice * discountRate / 100); } int main() { double finalPrice; finalPrice = calculateNetPrice(); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0;

Calculate the moment of inertia with regard to the X axis:

double MomentOfInertia(double b, double h) { return b * h * h * h / 3; }

int main() { double Base, Height; cout << "Enter the dimensions of the Rectangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nMoment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm" << "\n\n"; return 0;

Calculate the moment of inertia for a semi-circle:

double MomentOfInertia(double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; }

int main() { double base, height, radius; cout << "Enter the dimensions of the Rectangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nMoment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm"; cout << "\n\nEnter the radius: "; cin >> radius; cout << "Moment of inertia of a semi-circle with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; return 0; }

Function

prototype contains

Function name Parameters (data type) Return type (void if returns nothing) Only needed if function definition after function call

Prototype

must match function definition

Function prototype
double maximum( double, double, double );

Definition
double maximum( double x, double y, double z ) { }
25

Function signature

Part of prototype with name and parameters

double maximum( double, double, double );


Function signature

Argument Coercion

Force arguments to be of proper type

Converting int (4) to double (4.0)

cout << sqrt(4)

Conversion rules

Arguments usually converted automatically Changing from double to int can truncate data 3.4 to 3
int * double
26

Mixed type goes to highest type (promotion)

Da ta typ es long double double float unsigned long int (synonymous with unsigned long) long int (synonymous with long) unsigned int (synonymous with unsigned) int unsigned short int (synonymous with unsigned short) short int (synonymous with short) unsigned char char bool (false becomes 0, true becomes 1) Fig . 3.5 Pro m o tio n hiera rc hy fo r b uilt-in d a ta typ es.

27

Empty

parameter lists

void or leave parameter list empty Indicates function takes no arguments Function print takes no arguments and returns no value

void print(); void print( void );

28

3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

#include <iostream> using std::cout; using std::endl; void function1(); void function2( void ); int main() { function1(); function2(); return 0; } // end main // function1 uses an empty parameter list to specify that // the function receives no arguments void function1() { cout << "function1 takes no arguments" << endl; } // end function1 // function2 uses a void parameter list to specify that // the function receives no arguments void function2( void ) function1 takes no arguments { function2 also takes no arguments cout << "function2 also takes no arguments" << endl; } // end function2 // call function1 with no arguments // call function2 with no arguments // indicates successful termination // function prototype // function prototype

29

33 34

Call

by value

Copy of data passed to function Changes to copy do not change original Prevent unwanted side effects

Call

by reference

Function can directly access data Changes affect original

30

Reference

parameter

Alias for argument in function call


Passes parameter by reference

Use & after data type in prototype

void myFunction( int &data ) Read data is a reference to an int


However, original can now be changed

Function call format the same

31

1 2 3

// Comparing pass-by-value and pass-by-reference with references. #include <iostream> using std::cout;

Notice the & operator, 4 using std::endl; 5 indicating pass-by6 int squareByValue( int ); // function prototype reference. 7 void squareByReference( int & ); // function prototype 8 9 int main() 10 { 11 int x = 2; 12 int z = 4; 13 cout << "x = " << x << " before squareByValue\n"; 14 cout << "Value returned by squareByValue: << squareByValue( x ) << endl; 15 cout << "x = " << x << " after squareByValue\n" << endl; 16 // demonstrate squareByReference 17 cout << "z = " << z << " before squareByReference" << squareByReference( z ); 18 cout << "z = " << z << " after squareByReference" << endl; 19 20 return 0; // indicates successful termination Changes number, but 21 } // end main 22 int squareByValue( int number ) original parameter (x) is 23 { not modified. x = 2 before squareByValue 24 return number *= number; // caller's argument not modified 25 Value returned by squareByValue: 26 } // end function squareByValue x = 2 after squareByValue
27 28 29 30

Changes numberRef, an alias for the original void squareByReference( int &numberRef ) z = 4 before { parameter. Thus, z is squareByReference numberRef *= numberRef; // caller's argument modified changed. z = 16 after squareByReference
} // end function squareByReference
32

31

Binary

Search

Only used with sorted arrays Compare middle element with key

If equal, match found If key < middle Repeat search on first half of array If key > middle Repeat search on last half At most log2N steps, where N is the # of elements 30 element array takes at most 5 steps 2 > 30
1-33

Very fast

1 2 3 4 5 6 7 8

#include <iostream> #include <iomanip> using std::setw; int binarySearch( const int [], int, int, int, int ); int main() { const int arraySize = 15; // size of array a int a[ arraySize ]; // create array a

9
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

int key;
// value to locate in a for ( int i = 0; i < arraySize; i++ ) // create some data a[ i ] = 2 * i; cout << "Enter a number between 0 and 28: "; cin >> key; int result = binarySearch( a, key, 0, arraySize - 1, arraySize ); // display results if ( result != -1 ) cout << '\n' << key << " found in array element << result << endl; else cout << '\n' << key << " not found" << endl; return 0; // indicates successful termination } // end main

34

25 int binarySearch( const int b[], int searchKey, int low, int high, int size ) 26 27 { 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 } return -1; // searchKey not found } // end function binarySearch

Determine middle element


int middle; // loop until low subscript is greater than high subscript while ( low <= high ) { // determine middle element of subarray being searched middle = ( low + high ) / 2; // if searchKey matches middle element, return middle if ( searchKey == b[ middle ] ) // match return middle; else

Use the rule of binary search: If key equals middle, match


If less, search low end If greater, search high end

// if searchKey less than middle element, // set new high element if ( searchKey < b[ middle ] ) high = middle - 1; // search low end of array // if searchKey greater than middle element, // set new low element else low = middle + 1; // search high end of array

Enter a number between 0 and 28: 6 6 found in array element 3

Enter a number between 0 and 28: 25

Loop sets low, middle and high dynamically. If searching 25 not found the high end, the new low is the element above the middle.

Enter a number between 0 and 28: 8

8 found in array element 4 35

To

use a function inside of another function, that is, to call a function from another function, specify the name of the function and its list of arguments (if any) inside of parentheses; only the name of each argument is needed. You can declare a function like this:

Write a function that would calculate an items purchase price based on the items store price added the tax. The tax rate is a percentage value. This means that a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected on a purchase is taken from an items price; its formula is: TaxRate Tax Amount = Item Price * 100 The formula of calculating the final price of an item is: Final Price = Item Price + Tax Amount

double PurchasePrice(double itemPrice, double taxRate) { double price; price = itemPrice + (itemPrice * taxRate / 100); return price; }

int main() { double itemPrice, taxRate; double PurchasePrice(double itemPrice, double taxRate); cout << "Enter the price of the item: "; cin >> itemPrice; cout << "Enter the tax rate: "; cin >> taxRate; cout << "\nThe final price is: " << PurchasePrice(itemPrice, taxRate); cout << "\n\n"; return 0; } double PurchasePrice(double itemPrice, double taxRate) { double price;

price = itemPrice + (itemPrice * taxRate / 100); return price;


}

When

you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you call it and make use of its value. There are two major issues related to a variable: its value and its location in the memory.

The location of a variable in memory is referred to as its address. If you supply the argument using its name, the compiler only makes a copy of the arguments value and gives it to the calling function Although the calling function receives the arguments value and can use in any way, it cannot (permanently) alter it. C++ allows a calling function to modify the value of a passed argument if you find it necessary. If you want the calling function to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference.

To

pass an argument as a reference, when declaring the function, precede the argument name with an &.

void Area(double &side); // The argument is passed by reference bool Decision(char &answer, int age); // One argument is passed by reference // All arguments are passed by reference float Purchase(float &discountPrice, float &newDiscount, char &commission); The above would be called with: Area(side); Decision(answer, Age); Purchase(discountPrice, newDiscount, commission);

Write

a function that calculates employees weekly salary provided the total weekly hours and hourly rate.
that the employee claims to have worked 42 hours instead of the passed weekly hours.

Imagine

void Earnings(float &thisWeek, float salary) { thisWeek = 42; cout << "\n\nIn the Earnings() function,"; cout << "\n\tWeekly Hours = " << thisWeek; cout << "\n\tSalary = " << salary; cout << "\n\tWeekly Salary= " << thisWeek * Salary; }

int main() { float hours, rate, wage; void Earnings(float h, float r);

cout << "Enter the total Weekly hours: "; cin >> hours; cout << "Enter the employee's hourly rate: "; cin >> rate; cout << "\nIn the main() function,"; cout << "\n\tWeekly Hours = " << hours; cout << "\n\tSalary = $" << rate; cout << "\n\tWeekly Salary: $" << hours * rate; cout << "\nCalling the Earnings() function"; Earnings(hours, rate);
cout << "\n\nAfter calling the Earnings() function, " << "in the main() function,"; cout << "\n\tWeekly Hours = " << hours; cout << "\n\tSalary = " << rate; cout << "\n\tWeekly Salary: " << hours * rate; return 0; }

Você também pode gostar