Creating Functions
When we writing code, we often write a section of code that several lines, maybe four or five statements. And we figure out these lines kinda belong together. Perhaps these lines have the same objective in our program. We decided to take these lines of code and give it a name. We will make these lines as function, to create self contain chunk of code, like a mini program within our program. We then can use it, or reuse it, from other place in our code.
To create function we have to begin with three things :
- What it's called?
- Where it started?
- Where it ended?
Function myNewFunction
statement 1
statement 2
statement 3
...
End Function
Word 'Function' is different between languages, but the basic is similar. You have to know where it begin and finish using code block, like we learn before. Naming function is like naming variable, it's up to us but we want to name it something meaningful.
Because the code now place inside function, they will never be executed unless some other part of our program call it or access it. So when writing function we have to know two things : how to write it, and how to run it.
function printMessage {
print("Nice!")
}
printMessage();
Above is simple example how you call function. Different language have different way to do this, but most of them just calling it by writing the name of function followed by pair of parentheses.
Returning Value
The next step is often we want our function to do something and then return a value. We can do that by adding 'return' in the end of function.
function addingTwoNumber {
return 2+3
}
//call the function
int number = addingTwoNumber() //number now have value of 5
'number' calling function, and whatever return now assigned as its value.
Function with Parameter
Another way to use function is instead just hoping to get return value, we calling it while passing information to that function and expecting get new information. That's why we use function with parameter. Here's an example :
function addingTwoNumber(int number1, int number2)
{
int result = number1 + number2
return result
}
//call the function
int number = addingTwoNumber(2, 3) //number now have value of 5
The parameters in that function is in parentheses after function name. It means addingTwoNumber function can only be called if we give it value to work with. In the example, we give it value of 2 and 3 to added.
What value we able to pass is depends on parameters in function. You cannot pass integer values to string parameters. The same rules applied with number of parameters. If function have two paramaters, you cannot give it only one values.