CSC106 Intermediate PC Applications and Programming
Selection

Selection statements allow a program to perform different statements based on some condition. The condition usually consists of a comparison of two or more values. Simple comparisons are performed with relational operators. In VB the relational operators are:

Symbol Meaning
= equal
<> not equal
< less than
> greater than
<= less than or equal to
>= greater than or equal to

Here are some examples of pseudocode for selection operations:

   read time
   if time is 5pm
      print "go home"
   end if

   read gender
   if gender is female
      print "Dear Madam"
   else
      print "Dear Sir"
   end if

   read cholesterol
   if cholesterol >= 200
      print "your cholesterol is too high"
      print "please see your doctor"
   else
      if cholesterol >= 190
         print "be careful...your cholesterol is borderline"
      else
         print "your cholesterol is ok"
      end if
   end if

   if profit >= 0
      print "Profit: " profit
   else
      print "Loss: " profit
   end if

Notice that we indent the statement(s) that come after the if, and the statement(s) that come after the else. Without this the program is very difficult to read.

In VB, an if statement is formatted as follows:

     If condition Then
        statement(s) to execute if the condition is true
     Else
        statement(s) to execute if the condition is false
     End If
Here are some examples of VB code containing if statements:


' print either Sir or Madam

    gender = txtGender.Text
    If gender = "f" Then
       lblGreet.Text = "Dear Madam"
    Else
       lblGreet.Text = "Dear Sir"
    End If


' calculate sale price, tax, and total
' all items are 10% off, except audio (dept 336), which are 15% off

    deptnum = CInt(txtdept.Text)
    cost = CDbl(txtcost.Text)
    If deptnum = 336 Then
       cost = cost - cost * .15
    Else
       cost = cost - cost * .1
    End If
    tax = cost * taxrate
    totalcost = cost * tax


' calculate sale price, tax, and total
' items under $200 are 15 % off, items over $200 are 10% off

    cost = CDbl(txtcost.Text)
    If cost < 200 Then
       cost = cost * .85
    Else
       cost = cost * .9
    End If
    tax = cost * taxrate
    totalcost = cost * tax

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2007