Functions are not really necessary in programming, but they are a great way of making your code more readable for humans which is very important because you want to be able to understand your own code right?
In the last post I introduced conditions and loops which are quite essential for programming.
Functions usually consist of four to five parts:
void instead of the usual return value. Python again needs no specification of the return value and uses the type of the variable that is used in the return statement.return variableName;return variableNameHere is a small example how a function will look like in java:
You could also make the functions static if you wouldn't want to create a new Object and call them directly(without objectname+".").
You can create functions not inside of other functions bodys(unless you have some special case) and in java you can create functions like most other things only inside of a class.
You can also call a function from within itself:
void selfCall() {
selfCall();
}
If this function would be called once your program would get stuck trying to call one function infinitely often. Usually you will get a StackOverflow error there.
In some cases it is usefull to have function call itself. I will come back to this when talking about recursive algorithms.
The functions used in programming can be pretty similar to those you might know from maths:
f(x) = x² can be written in java as:
int f(int x) {
return x*x;
}
You can do the same with functions of multiple variables like:
g(x, a) = a*x²:
int g(int x, int a) {
return a*x*x;
}
There are also conditional functions in maths like the value function which can also be used in programming:
value(x) = x for x ≤ 0
value(x) = -x for x < 0
↓
int value(int x) {
if(x >= 0) {
return x;
}
return -x;
}
or:
int value(int x) {
int result;
if(x >= 0) {
result = x;
}
else {
result = -x;
}
return result;
}
Write a java function for the signum function:
sgn(x) = 0 for x = 0
sgn(x) = 1 for x > 0
sgn(x) = -1 for x < 0