190 likes | 309 Vues
Functions are essential components in programming that allow us to encapsulate logic and reuse code efficiently. They define a contract for performing actions with specific inputs and provide outputs via return statements. Each function has its own scope, with variables declared inside it being accessible only within that function. Understanding parameters and types is crucial for effective function usage. This guide covers the fundamentals of function declaration, naming conventions, and the importance of clear, readable code. Learn to leverage functions for cleaner and more effective programming!
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: