Top Banner
Chapter 3 Function Basics
38

Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Oct 18, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Chapter 3

Function Basics

Page 2: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Learning ObjectivesPredefined Functions

Those that return a value and those that don’t

Programmer-defined FunctionsDefining, Declaring, CallingRecursive Functions

Scope RulesLocal variablesGlobal constants and global variablesBlocks, nested scopes

Page 3: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Introduction to FunctionsBuilding Blocks of ProgramsOther terminology in other languages:

Procedures, subprograms, methodsIn C++: functions

I-P-OInput – Process – OutputBasic subparts to any programUse functions for these ‘pieces’

Page 4: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Predefined FunctionsLibraries full of functions for our use!Two types:

Those that return a valueThose that do not (void)

Must ‘#include’ appropriate librarye.g.:

<cmath>, <cstdlib> (Original ‘C’ libraries)<iostream> (for cout, cin)

Page 5: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Using Predefined FunctionsMath functions very plentiful

Found in library <cmath.h>Most return a value (the ‘answer’)

Example: theRoot = sqrt(9.0);Components:sqrt = name of library functiontheRoot = variable used to assign ‘answer’ to9.0 = argument or ‘starting input’ for functionIn I-P-O:

I = 9.0P = ‘compute the square root’O = 3, which is returned & assigned to theRoot

Page 6: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

The Function CallBack to this assignment:

theRoot = sqrt(9.0);The expression ‘sqrt(9.0)’ is known as afunction call, or function invocationThe argument in a function call (9.0) can be aliteral, a variable, or an expressionThe call itself can be part of an expression:

bonus = sqrt(sales)/10;A function call is allowed wherever it’s legal to usean expression of the function’s return type

Page 7: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

A Larger ExampleDisplay 3.1, page 94

Page 8: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

More Predefined Functions#include <cstdlib>

Library contains functions like:abs() // Returns absolute value of an intlabs() // Returns absolute value of a long int*fabs() // Returns absolute value of a float

*fabs() is actually in library <cmath>!Can be confusingRemember: libraries were added after C++ was‘born’, in incremental phasesRefer to appendices/manuals for details

Page 9: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

More Math Functionspow(x, y)

Returns x to the power ydouble result, x = 3.0, y = 2.0;result = pow(x, y);cout << result;

Here 9.0 is displayed since 3.02.0 = 9.0

Notice this function receives twoarguments

A function can have any number ofarguments, of varying data types

Page 10: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Even More Math FunctionsDisplay 3.2, page 96

Page 11: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Predefined Void FunctionsNo returned valuePerforms an action, but sends no ‘answer’When called, it’s a statement itself

exit(1); // No return value, so not assignedThis call terminates programvoid functions can still have arguments

All aspects same as functions that ‘returna value’

They just don’t return a value!

Page 12: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Random Number GeneratorReturn ‘randomly chosen’ numberUsed for simulations, games

rand()Takes no argumentsReturns value between 0 & RAND_MAX

ScalingSqueezes random number into smaller rangerand() % 6Returns random value between 0 & 5

Shiftingrand() % 6 + 1

Shifts range between 1 & 6 (e.g.: die roll)

Page 13: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Random Number SeedPseudorandom numbers

Calls to rand() produce given ‘sequence’of random numbers

Use ‘seed’ to alter sequencesrand(seed_value);

void functionReceives one argument, the ‘seed’Can use any seed value, including system time:srand(time(0));time() returns system time as numeric valueLibrary <time> contains time() functions

Page 14: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Random ExamplesRandom double between 0.0 & 1.0:(RAND_MAX – rand())/static_cast<double>(RAND_MAX)

Type cast used to force double-precision division

Random int between 1 & 6:rand() % 6 + 1

‘%’ is modulus operator (remainder)Random int between 10 & 20:rand() % 10 + 10

Page 15: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Programmer-Defined FunctionsWrite your own functions!Building blocks of programs

Divide & ConquerReadabilityRe-use

Your ‘definition’ can go in either:Same file as main()Separate file so others can use it, too

Page 16: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Components of Function Use3 Pieces to using functions:

Function Declaration/prototypeInformation for compilerTo properly interpret calls

Function DefinitionActual implementation/code for what function does

Function CallTransfer control to function

Page 17: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Function DeclarationAlso called function prototoypeAn ‘informational’ declaration for compilerTells compiler how to interpret calls

Syntax:<return_type> FnName(<formal-parameter-list>);Example:double totalCost( int numberParameter,

double priceParameter);

Placed before any callsIn declaration space of main()Or above main() in global space

Page 18: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Function DefinitionImplementation of functionJust like implementing function main()Example:double totalCost( int numberParameter,

double priceParameter){

const double TAXRATE = 0.05;double subTotal;subtotal = priceParameter * numberParameter;return (subtotal + subtotal * TAXRATE);

}

Notice proper indenting

Page 19: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Function Definition PlacementPlaced after function main()

NOT ‘inside’ function main()!Functions are ‘equals’; no function is ever‘part’ of anotherFormal parameters in definition

‘Placeholders’ for data sent in‘Variable name’ used to refer to data in definition

return statementSends data back to caller

Page 20: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Function CallJust like calling predefined functionbill = totalCost(number, price);Recall: totalCost returns double value

Assigned to variable named ‘bill’Arguments here: number, price

Recall arguments can be literals, variables,expressions, or combinationIn function call, arguments often called ‘actualarguments’

Because they contain the ‘actual data’ being sent

Page 21: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Function ExampleDisplay 3.5, page 105

Page 22: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Alternative Function DeclarationRecall: Function declaration is ‘information’for compilerCompiler only needs to know:

Return typeFunction nameParameter list

Formal parameter names not needed:double totalCost(int, double);

Still ‘should’ put in formal parameter namesImproves readability

Page 23: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Parameter vs. ArgumentTerms often used interchangeablyFormal parameters/arguments

In function declarationIn function definition’s header

Actual parameters/argumentsIn function call

Technically parameter is ‘formal’ piecewhile argument is ‘actual’ piece*

*Terms not always used this way

Page 24: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Functions Calling FunctionsWe’re already doing this!

main() IS a function!Only requirement:

Function’s declaration must appear firstFunction’s definition typically elsewhere

After main()’s definitionOr in separate file

Common for functions to call many otherfunctionsFunction can even call itself ‘Recursion’

Page 25: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Boolean Return-Type FunctionsReturn-type can be any valid type

Given function declaration/prototype:bool appropriate(int rate);And function’s definition:bool appropriate (int rate){

return (((rate>=10)&&(rate<20))||(rate==0);}Returns ‘true’ or ‘false’Function call, from some other function:if (appropriate(entered_rate))

cout << “Rate is valid\n”;

Page 26: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Declaring Void FunctionsSimilar to functions returning a valueReturn type specified as ‘void’Example:

Function declaration/prototype:void showResults( double fDegrees,

double cDegrees);Return-type is ‘void’ Nothing is returned

Page 27: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Declaring Void FunctionsFunction definition:void showResults(double fDegrees, double cDegrees){

cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(1);cout << fDegrees

<< “ degrees fahrenheit equals \n”<< cDegrees << “ degrees celsius.\n”;

}

Notice: no return statementOptional for void functions

Page 28: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Calling Void FunctionsSame as calling predefined void functionsFrom some other function, like main():

showResults(degreesF, degreesC);showResults(32.5, 0.3);

Notice no assignment, since no valuereturnedActual arguments (degreesF, degreesC)

Passed to functionFunction is called to ‘do it’s job’ with thedata passed in

Page 29: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

More on Return StatementsTransfers control back to ‘calling’ function

For return type other than void, MUST havereturn statementTypically the LAST statement in functiondefinition

return statement optional for void functionsClosing } would implicitly return control fromvoid function

Page 30: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Preconditions and PostconditionsSimilar to ‘I-P-O’ discussionComment function declaration:void showInterest(double balance, double rate);//Precondition: balance is nonnegative account balance// rate is interest rate as percentage//Postcondition: amount of interest on given balance,// at given rate …

Often called Inputs & Outputs

Page 31: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

main(): ‘Special’Recall: main() IS a function‘Special’ in that:

One and only one function called main()will exist in a program

Who calls main()?Operating systemTradition holds it should have return statement

Value returned to ‘caller’ Here: operating systemShould return ‘int’ or ‘void’

Page 32: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Scope RulesLocal variables

Declared inside body of given functionAvailable only within that function

Can have variables with same namesdeclared in different functions

Scope is local: ‘that function is it’s scope’Local variables preferred

Maintain individual control over dataNeed to know basisFunctions should declare whatever local dataneeded to ‘do their job’

Page 33: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Procedural AbstractionNeed to know ‘what’ function does, not‘how’ it does it!Think ‘black box’

Device you know how to use, but not it’smethod of operation

Implement functions like black boxUser of function only needs: declarationDoes NOT need function definition

Called Information HidingHide details of ‘how’ function does it’s job

Page 34: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Global Constants and Global Variables

Declared ‘outside’ function bodyGlobal to all functions in that file

Declared ‘inside’ function bodyLocal to that function

Global declarations typical for constants:const double TAXRATE = 0.05;Declare globally so all functions have scope

Global variables?Possible, but SELDOM-USEDDangerous: no control over usage!

Page 35: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

BlocksDeclare data inside compound statement

Called a ‘block’Has ‘block-scope’

Note: all function definitions are blocks!This provides local ‘function-scope’

Loop blocks:for (int ctr=0;ctr<10;ctr++){

sum+=ctr;}

Variable ctr has scope in loop body block only

Page 36: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Nested ScopeSame name variables declared inmultiple blocksVery legal; scope is ‘block-scope’

No ambiguityEach name is distinct within it’s scope

Page 37: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Summary 1Two kinds of functions:

‘Return-a-value’ and void functionsFunctions should be ‘black boxes’

Hide ‘how’ detailsDeclare own local data

Function declarations shouldself-document

Provide pre- & post-conditions in commentsProvide all ‘caller’ needs for use

Page 38: Chapter 3 - cs.wmich.edualfuqaha/cs111/lectures/lec5.pdf · No returned value Performs an action, but sends no ‘answer’ When called, it’s a statement itself exit(1); // No return

Summary 2Local data

Declared in function definitionGlobal data

Declared above function definitionsOK for constants, not for variables

Parameters/ArgumentsFormal: In function declaration and definition

Placeholder for incoming dataActual: In function call

Actual data passed to function