S.B.C.C. ->
Computer Science -> Courses
-> COMSC 111 -> Class
Notes
This program is used to get an age value and
then check to see if a person is older than 21 or not. If they are then
the program prints out that they can drink, if not, then it prints out
that they cannot drink.
One difference between this algorithm and the code is that the code gets the age and validates it. This shows that you can do algorithm design on many levels. Try to shoot for enough detail to get the point across but not to do every single step. However, it's better to err on the side of too much detail than not enough. |
![]() |
<script language="JavaScript">
This tag indicates that what follows is JavaScript. I didn't use "JavaScript1.1" because we are not using any 1.1 specific features. The next line is
var age;
This is a declaration of the variable age to be used later. This is actually optional but I've got it on there for completness.
if((age = prompt("What is your age?", ""))
!= null)
{
... block 1, done if the condition
is true ...
}
else
{
... block 2, done if the condition
is false ...
}
The if statement combines assignment with comparison. The inner parens (the ones containing the "age =" portion) put up the prompt dialog. The dialog is shown below.
Once something is placed in the prompt dialog and the "OK" button is pressed, then that value is placed into the age variable. If a person presses the cancel value then nothing is placed into the age variable and the value of age is null. Null means nothing (NOT ZERO) and is a special value in JavaScript. After age is filled in, with either a value or null, it is compared to null. If it isn't null, then something has been entered and the block 1 JavaScript is executed. If the cancel button has been pressed than the JavaScript in block 2 is executed.
if(age >= 21)
{
document.write("<b>Drink</b>");
}
else
{
document.write("<b>No</b>
Drink");
}
document.write("You <b>must</b> answer!");
The final line is a tag which closes off the script block.
</script>
Last
Updated: March, 1998