| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Stop wasting time looking for files and revisions. Connect your Gmail, DriveDropbox, and Slack accounts and in less than 2 minutes, Dokkio will automatically organize all your file attachments. Learn more and claim your free account.

View
 

Selection using IF-THEN-ELSE in Turing

Page history last edited by Steve Sweeney 11 years, 9 months ago

Selection is the process of making a decision based upon the available data.  All decisions in a programming language are based on a condition, or multiple conditions.  It is important to remember to write our conditions so they can resolve to either true or false, depending on the data.

 

Conditions, or conditional statements, use the Relational Operators to compare values (see link to refresh your memory of relational operators)

 

The simplest form of selection is the IF statement.

 

if (condition is true) then do something

 

In Turing, the IF statement has a specific form.  In this case, we are only interested in the true outcome for the selection, so we have one possible outcome.

 

if (age >= 16) then

     put "You are old enough to drive"

end if

 

For situations where we are interested in both the true and the false outcome, we add the else statement, and now have two possible outcomes.

 

if (age >= 16) then

     put "You are old enough to drive"

else

     put "Sorry, you're not ready to drive yet."

end if

 

For more than two outcomes, it is possible to use nested-if statements to handle the logic.  Fortunately, Turing provides a simpler form called the "else if", which Turing writes as "elsif".  This allows a condition for each outcome.  It is important to note that the conditions will be evaluated in order, and the first true condition is the only one that gets processed!  Compare the following fragments of code:

 

Example 1 - works correctly Example 2 - will not catch older drivers

if (age >= 70) then

     put "You can drive after an eye exam"

elsif (age >= 16)

     put "You are old enough to drive"

else

     put "Sorry, you're not ready to drive yet."

end if

if (age >= 16) then

     put "You are old enough to drive"

elsif (age >= 70)

     put "You can drive after an eye exam"

else

     put "Sorry, you're not ready to drive yet."

end if

 

It is possible to create more complicated selection statements by using multiple conditions.  Conditions are combined through the use of the Logical Operators (and, or).

 

if ( age >= 18 ) and ( citizenship = "Canadian" ) and ( validIdentification >= 2 ) then

     put "Allow this person to vote here."

else

     put "This person must fill out a special form in order to vote."

end if

 

 

Comments (0)

You don't have permission to comment on this page.