Worked Example



Function to Calculate the Area of a Circle

What we know

Area of a circle is 3.14 * radius * radius

For this exercise, we will need to do the following:

  1. set a value for the radius in the main routine
  2. call a function to take that value and do the calculation
  3. output the result to the console



How we start

We start with the skeleton for the code. There should be:

  • a main() function
  • a function for the calculation
  • and a call to the function

This should all be enclosed in the JQuery for loading the document

image of fucntion


Calling the Function and Outputting

In the main() routine, we add some code that will call function to do the calculation and output the result

This all takes place on one line of code.

  • calling the function means using the name of the function in the line of code.
  • In other words, the execution of the code is routed to the function code
  • Once the function code has completed, the execution of the code returns to the line from which it has been called.

You can see that here:

image of fucntion


Writing the function

The function needs to receive a value to use. We use a named placeholder for this value. In the main() routine it is passed as a number but in the function it is represented with a name. We call call this "passing a parameter"

The named placeholder is a variable when it is inside the function (i.e. it's value is not fixed until the function is passed the value).

The function uses the variable to carry out the calculation. This is just like algebra where we have letters that are then substitued for actual values when the algebra is used.

So,

  • the parameter needs to be inside the brackets in the function title.
  • the parameter is then used in the fucntion code
  • Once the function code has completed, the value is returned to the line from which it has been called.

You can see that here:

image of fucntion