You have been calling functions since Week 1: main is one, and so are max,
min, abs and sqrt. You give max(4, 9) two numbers, it does its job, and
you get one number back — without knowing or caring how it works inside.
This week you write your own. A function is a piece of code with a name:
you write it once, and then call it by name as often as you like. Programs
stop being one long main and become a few small parts, each with one job.
Your first function
Here is a function that squares a number:
| Part | What it means |
|---|---|
int (before the name) | the return type: the function gives back an int |
square | the function's name |
(int x) | the parameter: a variable that receives the value it is called with |
{ … } | the body: the code that runs at every call |
return x * x; | ends the call and hands the value back |
Writing the function runs nothing. Its body runs when somebody calls it:
In square(7), the value 7 is the argument. At the call, the parameter
x is created and gets the value 7; the body works out 49; return hands 49
back to the place of the call, and simply 49 there.
Parameters are the variables in the definition; arguments are the values in a
particular call.