Simple Tests and Conditions
The power of computers to solve complicated problems relies
on their ability to a) carry out similar operations many times,
and b) to make decisions depending on the outcome of previous
calculations.
For simple calculations the first of these is less important,
although it is crucial to more complicated ones, so we will
discuss it later.
We will now look at how to carry out simple tests in programs.
Any of the instructions we have considered so far can be made
conditional on some test by preceding it with:
if (test) .....
The test will usually be an expression involving
mathematical comparison operators such as `<' (`less than'),
`>' (`greater than') or others listed below.
Example
We want to calculate the square root of a number. However,
if the number is negative, it does not have a normal square root,
it is in fact what is called an imaginary number.
To test whether the value of a variablex is positive (>0) and if so calculate and display its
square root we can use the following instruction:
if (x>0) document.write (Math.sqrt(x))
Here is a program which does this,
and also tells the user if the square root is imaginary.
If you look at the text of the above program you will see
that I have written the test as:
if (x>=0) document.write (Math.sqrt(x))
This allows for the situation where x is greater than or equal to zero,
which is quite legitimate.
The full set of relational operators of this kind is as follows:
- < - less than
- <= - less than or equal to
- > - greater than
- >= - greater than or equal to
- == - equal to, NB not just =
- != - not equal to
What You Should Now Be Able to Do
This introduction to programming has now covered everything
in Javascript you need to be able to do in a program what you
might otherwise do with a spreadsheet. There are many things
that programs can do that spreadsheets cannot. If you want to
find out about some of them, you might like to look through
these notes
of further ideas. (Note that the present version of these notes
in not specifically intended for radio amateurs.)