Creating functions#
We have introduced functions before in section Arguments and return value in functions. This time we will create our own.
But why?
To reuse our code somewhere else.
Make our code easier to read by summarizing a block of code with a meaningful name.
For example:
Without functions
double[] dest1 = [3, 7], dest2 = [3, 4];
// Robot tool destination coordinates on a surface.
var distance = Math.Sqrt(Math.Pow(dest1[0], 2) + Math.Pow(dest1[1], 2));
Console.WriteLine($"Robot tool will move {distance:F2} m");
distance = Math.Sqrt(Math.Pow(dest2[0], 2) + Math.Pow(dest2[1], 2));
Console.WriteLine($"Robot tool will move {distance:F2} m");
With functions
double[] dest1 = [3, 7], dest2 = [3, 4];
// Robot tool destinations
double Distance(double[] coordinates)
{
return Math.Sqrt(Math.Pow(coordinates[0], 2) + Math.Pow(coordinates[1], 2));
}
Console.WriteLine($"Robot tool will move {Distance(dest1):F2} m");
Console.WriteLine($"Robot tool will move {Distance(dest2):F2} m");
Activity 26 (Writing a function)
Above example has still repetitive code. Create an additional function that gets rid of repetitive code.
Activity 27
Write a function that returns the distance between two three dimensional points.
parameters: two points. Each point is an array of three numbers in meters.
return: a number in meters
Choose a meaningful name for the function.