Making DecisionsOften you will want a program to make decisions and perform different actions depending on particular conditions.
To do this you can use If…else statements. For example, if a school year greater than 13 was entered, the program could return a statement like 'This year group is too high' otherwise (else) it could return 'this year group is in the required range'.
The program can also be made to select from a range of alternatives depending on the value entered using CASE statements.
Click the arrow to view some examples.
if(guess == random number) print "Well done"
else
print "No. Bad guess"
if(guess > random number) print "Guess is too high"
else
print "Guess is too low'
IF…Else Statements
This is an example of a program where the computer has to decide if a number you enter is equal to, greater than or less than a random number it has had to selected.
click RUN to start
Press after number entered
Create a random number
RUN
Ask for user guess - please enter a guess between 1 and 100
You selected option
A
Click the arrow to see the code for this quiz.
B
Using the CASE statement
C
E
Cities of the world quiz
Tap or click on the picture of Rome
D
var pick = (A, B, C, D or E depending on the image selected);
{case A:
messageBox.innerHTML = 'Sorry. This is Venice.';
break;
case B:
messageBox.innerHTML = 'Sorry. This is Florence.';
break;
case C:
messageBox.innerHTML = 'Well done. You selected Rome.';
break;
case D:
messageBox.innerHTML = 'Sorry. This is Istanbul.';
break;
case E:
messageBox.innerHTML = 'Sorry. This is Barcelona.';
break;
}
switch(pick)
Move your mouse over a statement to hear an explanation.