Lecture 3

Doing Calculations

calculation of one of the roots of a quadratic equation

Writing a Program for Calculations

Important note: This short section covers the most important ideas for the practicals 7 to 12. Take it down completely. It describes the complete procedure for writing a computer program for doing calculations, which is the objective of the first half of this JavaScript course. The example is particularly important. Later you will be asked in asignments to write programs. It is well worth while, always referring back to this example and modelling your program on it.

The following set of instructions uses a formula for calculating "Distance travelled" (s) of an object, when the "Initial Velocity" (u), "Accelleration applied" (a) and the "Length of time" (t) the accelleration is applied for are known, according to the formula s = ut + 1/2at2 Read over these instructions, have a look at the example below it, and then read over them again, referring each line to the example below.

initialV

acc

time

dist

Below is an example of a program to do the above calculation. On the left are the variables in the computer's memory. Read the program carefully, then run it by pressing the button below and watch the effect on the variables on the left. Try to figure out what the effect of each instruction is.

initialV=promptNumber("Enter the initial velocity!")
acc=promptNumber("How much acceleration is applied?")
time=promptNumber("How many seconds have elapsed?")
dist=initialV*time+0.5*acc*time*time
alert("The total distance travelled is: " + dist)

The example above may be a little complicated, if you feel you have not fully understood it, Click here for a simpler example.

Priority and Parentheses (brackets)

The order of priority for calculations ( the order it likes to do calculations in) is

  1. * (multiplication) / (division)
  2. + (addition) - (subtraction)

This means, that it generally prefers to do multiplication and division before addition and subtraction. (If there are several operations of the same priority in the calculation, it will do the one on the left first)

Exercise: Calculate x + 4 * y / 2 * x + y where x is 2 and y is 3.

Type your answer here:

However, these priorities may be overridden by parentheses (brackets). When you use brackets, you have to complete the calculation within the brackets before ones outside it.

Now calculate (x + 4 * y) / (2 * x + y ) with the same values for x and y.

Type your answer here:

End of Lecture: To go back to where you came from click on Back on the toolbar.