All about Functions
Java
Key things to note:
If you don’t know this, it won’t matter too much for Level 2.
But it can make other problems easier and it’s definitely a skill you would want if you are going for Excellence.
Unfortunately it’ll just be a longish lecture from Mr Chuang to go over it!
Don’t bother taking notes, I’ll share the code as we go.
Functions - Linking back to what you know
You have seen functions before by now if you have done L2 MATH.
Y = sin(x)
Y = Log(x)
Y = x^2
Even this one!
Y = x + 1
How to think about them
You have a rule or inputs, the rule “processes” the input, and we get an output!
Example:
Y = x + 1
Input: 2 -> Output: 3
Input: 5 -> Output: 6
In L2 MATH Terms
NOTE: 3) will not be true in Computer Science.
This is also not true in what we call Discrete Mathematics!
Examples of “invalid” functions
Sqrt(x)
Equations that draws Circles
A bunch of other stuff that’s beyond the scope.
Such as:
arcsin(x)
Have you tried graphing that before?
In Computer Science.
Definition of a function:
A function is a rule that takes inputs and produces outputs.
Note: The restriction for number of inputs/outputs is no longer here!
Here’s a picture
You will see many f(x) in the future!
Basically f(x) is the same as y.
1 input -> Many outputs #1
Think of this scenario:
Input: a first name
Output: Their email, phone number, address
Hopefully this isn’t too strange to think that a function can do this.
1 input -> Many output #2
Sqrt(x)
Input: 9
Output: 3, -3
Other examples:
Many to one:
Input: length, width
Output: Area
Input: First Name, Last Name
Output: Age
Other examples #2
Many to Many:
Inputs: Length, Width, Height:
Outputs: Area needed to paint, Paint Needed, Number of Buckets needed to purchase
In BlueJ
Code in comments.
There are variables in the brackets, they are the inputs!
Note the return type is what the output is!
More examples…
Unfortunately most of these are math examples!
Something that’ll speed things up!
The Quiz…What we want to avoid!
Technically this does work…
But it’s much more efficient if we do something different!
Check the comments if you want to see the original code.
How to fix this…
Mr Chuang will be improvising this.
He’ll also need to talk about global variables and fields!
(He did this in 2023, the answers are in the comments below)