Turing/If statements, cases

From Wikibooks, open books for an open world
Jump to navigation Jump to search

If statements are just that. They say, "If a is true, then do the following, if not, do this instead"

Here's a simple program for you that tests if someone is an adult.

var age : nat %Can't have negative age

get age

if age < 18 then
     put "You are not an adult!"
else
     put "You are an adult!"
end if

This program is saying: "Ask the user for their age. If it's under 18, then they're not an adult. If it's not under 18, then they are. Note that else statements do not check if they are greater/equal to 18, they just check if they are not under 18. This will suffice for our purposes

But what if we want to test for seniors too? This can be accomplished with an elsif statement:

...
if age < 18 then
     put "You are not an adult!"
elsif age > 64 then
     put "You are a senior!"
else
     put "You are an adult!"
end if

This is saying "If they are under 18, they're not an adult. If they're not under 18, then check if they're older than 64; if so, they are a senior. If neither of the above cases are true, then they are an adult.

Cases are like funny if-statements. They're pretty easy to understand, but you probably won't use them until later. Still, they fall under the same category as if statements, so you might as well get used to them now.


Hello world · Loops

Hello world · Turing · Loops