Functions

=Functions=

Functions allow compartmentalization of your program. Basically, this allows you take a large task and break it down into smaller tasks. One term that you will here is calling of a function. Calling a function requests that it be run at that time. A function can also return information back to the main program.

What does a function look like? (See Below)

code format="csharp" public double multiply(double x, double y)       { return x * y;       } code The functions name is multiply and will return a value when it is called of the type double. It takes two inputs that are both of the type double. To use this function you would do send it two numbers and store the results in a variable. Below is how a function can be called.

code format="csharp" double result; result = multiply(3,3) code

This would multiply 3 and 3 then store 9 in the result variable after receiving 9 from the function.

Functions can return results or perform a set of commands and return nothing. Typically, a function would return information once it has performed some calculations.

To perform a set of commands the function would need to be told not to send anything back. To do this you use the term void. code format="csharp" public void GoHome {    //go straight on Fellows //Turn Left on Ewing //Turn Right on Ironwood { code This would be called from the main function like this:

code GoHome; code

Since this uses the void keyword the program will not expect to receive any information from the function. You would be able to set this up to recieve information from the main program and use that in the function.

code public void GoHome(int hours) {  //wait hours //go straight on Fellows //Turn Left on Ewing //Turn Right on Ironwood } code This is how this would be called from the program:

code format="csharp" GoHome(3); code

This could be used to have a loop run x number of times or wait so long before running the rest of the function.

Variables can be used to replace all of the numbers in the above examples in order to make everything a little bit more flexible.