Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page


Chapter 5 - 'if'

Here are the JT conditions:

==   equal to
!=   not equal to
>    greater than
<    less than
<=   less than or equal to
>=   greater than or equal to
They are called 'relational operators'.

We can also combine several conditions using logical operators:


	&&    	and
	||    	or
	!     	not
Brackets (...) may also be used to group conditions.

Let's look at some conditions in isolation, prior to using them in 'if' statements.



int n=1, m = 2; // declare a few vars for examples
double x=3.67,y=0.0;
We can now use these variables in conditions, e.g:

n < 3                    is true
m == 1                   is true
x >= 4.0                 is false

(n < 3) && (m == 1)      is true
(n < 3) || (m == 1)      is true

(n < 3) && (x >= 4.0)    is false
(n < 3) || (x >= 4.0)    is true

!(m == 1)                is false
(Note that the above is not a complete program. We need to cover 'if' before full programs can be written).

These examples illustrate that    ||    &&     !     work like boolean operators in maths i.e.

- when we 'or' a series of expressions together, we only need one to be true to make the whole expression true.

- when we 'and' a series of expressions together, each one must be true to make the whole expression true.

Note that the 'equal to ' condition is written


==

not as

 =
A single = is used for assignment.

The operators cannot be used on strings - only numbers.

The if statement

We use the keywords 'if', 'else' and to show a choice between two alternatives, as in:

Note:

Following the word 'if' we must put a condition, which is true or false.

If it is true, the statements within the first set of { } will be done, as far as 'else'. If the condition was false, the second group of statements within {...} will be done.

- the condition MUST be enclosed in round brackets.

- The two options can contain any number of instructions.

- If 'else' sounds awkward, interpret it in your head as 'otherwise'.

The second option might not be needed in certain problems, so we may put e.g:

if(age < 12)
{
alert("Too young");
}

Code formatting - pretty

You will soon see that programs have lots of curly brackets (braces). Programs are much easier to read if we can identify which opening and closing braces match up.

Click the Pretty button. You will see that the code is indented, giving:


function void main()
{
    int age = 0;
    age = getInt("Type your age");
    if(age<20)
    {
        print ("you are young");
    }
    else
    {
        print("sorry - old!");
    }
    alert("done");
}

Choosing and, or

A program to ensure that an age is between 16 and 64:

if((age>=16) || (age<=64))  // wrong
{
  alert("age ok");
}
We have chosen to put extra brackets in the conditions - that is fine. The real problem is the use of ||, meaning 'or'. Consider an age of 100. This is greater than 16, so the first condition is true. When we use 'or', the overall result is true if either of the conditions is true.

We should use && (and). The overall result is true only if the first and the second condtions are true.

Nested Ifs

Nesting - putting statements inside other statements. The nesting must be complete, in the sense of
{
    {

    }
}
Often, we nest if's to get a multiple-choice 'if', as in:

In the above, we are expressing the situation where there is a list of conditions, one of which will be true, and a list of actions for each case. The final 'else' is a 'catch-all' if none of the other conditions were met. This pattern is very common. Note the use of {...}. It is essential to pretty-print such code, as we have done.

Using Else

For beginners, it is tempting to regard 'else' as an optional extra. Consider a program which inputs a number, rejecting it if negative or processing it in some way if positive. We could code it as:

n = getInt("Type a positive number");
if (n<0)
{
    print("Error!");
}
// now process it
if (n>=0)
{
    ... process it
}
It is clearer to put:

n = getInt("Type a positive number");
if (n < 0)
{
    print("Error!");
}
else
{
    ... process it
	
}

Key Points

In complicated conditions, be careful in your choice of &&    ||.

Consider using extra brackets (...) in conditions to clarify the meaning of the program.

Problems

1. Write a program which reads in a double number and prints the square of it. An error message should be printed if the number is negative, and the answer should not be printed.

2. As Q1, but a warning message should be printed. In any case, square the number and print the answer.

3. Write a program to read in the dimensions of a rectangle and print its area. An error message should be printed if any dimension is negative.

4. Write a program to read in two integers, and to print them in ascending order.

5. Input 3 integers, and display an alert stating whether they are all equal or not.

6. Input an age, and display a message stating "Available for work" if in range 16 to 64 inclusive. If not, display "out of range".

7. Input 3 numbers, and print the biggest.


Ch1 - Output   .   Ch2 - Sequence    .   Ch3 - Variables    .    Ch4 - Input

Ch5 - If decisions    .    Ch6 - While loops   .    Ch7 - Functions

JT Home Page