190 likes | 300 Views
Writing Functions. The Big Idea. What if this was how we did powers?. Information. F unction header specifies everything but job of function A contract to do work. Review. A function declaration : Prototype Statements that do work of the function. A Function. A function:
E N D
The Big Idea • What if this was how we did powers?
Information • Functionheader specifies everything but job of function • A contract to do work
Review • A functiondeclaration : • Prototype • Statements that do work of the function
A Function • A function: -Called max -Takes two inputs (ints) -Gives back an int
Using Max • Using Max:
Full Program • Must declare afunction beforeit is used
Function Name • Function name • Normal identifier rules • no spaces, can't start with number, etc… • Use camelCase • Clearly identify job • Readability > terseness • Focus on verbs
Body • Body of a function – where magic happens • Always a block of code { } • Has own scope • Variables declared inside only available inside
Parameters • Parameters : information function needs • Declare with: type name, type name, type name… • OK to have no parametersintgetHourOfDay()…
Parameters • Parameters are special variables • Only exist within this function • Initialized with value caller passes in:abs(10) number = 10
Function type • returnstatement used to pass answer back • Must return right type of data
Function type • returnstatement used to pass answer back • OK to have more than one return • Every path must return
Void Functions • Void : nothing • Void function type returns nothing • Just does some work • Returns at }
Call Stacks • Each function works in a separate stack frame in memory
Rules For Functions • Only variable available are: • Parameters • New variables you declare in function
Rules For Functions • Do NOT use cin/cout
Rules For Functions • Do NOT use cin/cout • Unless job of function is to print or get input
Comparison Return a grade: Print a grade: