Home

Conditional Statements

 

Conditions

 

Introduction

When performing assignments using code, sometimes you must find out whether a given situation bears a valid value. This is done by checking a condition. To support this, VBScript provides a series of words that can be combined to perform validations. Checking a condition usually produces a True or a False result. Once the condition has been checked, you can use the result (as True or False) to take action. Because there are different ways to check a condition, there are also different types of keywords to check different things. To use them, you must be aware of what each does or cannot do so you would select the right one.

The Boolean Type

Sometimes, you may want to store the result of a condition, being true or false, in a variable. To do this, you can declare a variable that would hold a Boolean value. Here is an example of declaring a Boolean variable when the form opens:

Dim IsMarried

When a Boolean variable has been declared, you can assign it a True or a False value.

To convert a value or an expression to Boolean, use the CBool() function.

Techniques of Checking a Condition

 

The If...Then Statement

The simplest technique used to validate a condition is to check whether it is true. This can be done using an If...Then statement. The formula to use is:

If ConditionToCheck is True Then Statement

The program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement.

There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this:

If ConditionToCheck is True Then Statement

If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. The formula used is:

If ConditionToCheck is True Then
    Statement
End If
 

Practical Learning: Using If...Then

  1. Start Notepad or your text editor and type the following:
     
    <%@ Language="VBScript" %>
    <html>
    
    <head>
    
    <title>CD Publisher</title>
    </head>
    
    <body>
    
    <h1>CD Publisher</h1>
    
    <form method="GET" action="cdpublisher2.asp">
      <table border="0" width="553">
        <tr>
          <td width="191">Number of CDs Ordered:</td>
          <td width="113"><input type="text" name="txtQuantity" size="10"
            value=<% =Request.QueryString("txtQuantity") %> >
          </td>
          <td width="67"><input type="submit" value="Calculate" name="btnCalculate"></td>
          <td width="162"><input type="reset" value="Start New Order" name="btnReset"></td>
        </tr>
      </table>
    </form>
    
    <%
        Dim Quantity
        Dim UnitPrice
        Dim TotalPrice
        Dim strCD
    
        Quantity = CInt(Request.QueryString("txtQuantity"))
    
        strCD = "CDs"
        If Quantity = 1 Then strCD = "CD"
        
        Response.Write("<p>Since you ordered " & Quantity & " " & strCD & ",<br>")
        
        UnitPrice = 8.50
        If Quantity < 50 Then UnitPrice = 6.25
    
        Response.Write("Each CD will cost:      " & UnitPrice & "<br>")
        TotalPrice = Quantity * UnitPrice
        Response.Write("And the total price is: " & TotalPrice & "</p>")
    %>
    
    </body>
    
    </html>
  2. Save the file as cdpublisher2.asp in your Small Business folder 
  3. Access the browser. Change the address to http://localhost/smb/cdpublisher2.asp and press Enter
  4. Enter a number in the Quantity text box and click Calculate
     
  5. Return to your text editor
 

The If...Then...Else Statement

The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternative in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is:

If ConditionToCheck is True Then
    Statement1
Else
    Statement2
End If

When this section of code executes, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

 

Practical Learning: Using If...Then...Else

  1. To use If...Then...Else, change the code as follows:
     
    <%@ Language="VBScript" %>
    <html>
    
    <head>
    
    <title>CD Publisher</title>
    </head>
    
    <body>
    
    <h1>CD Publisher</h1>
    
    <form method="GET" action="cdpublisher2.asp">
      <table border="0" width="553">
        <tr>
          <td width="191">Number of CDs Ordered:</td>
          <td width="113"><input type="text" name="txtQuantity" size="10"
            value=<% =Request.QueryString("txtQuantity") %> >
          </td>
          <td width="67"><input type="submit" value="Calculate" name="btnCalculate"></td>
          <td width="162"><input type="reset" value="Start New Order" name="btnReset"></td>
        </tr>
      </table>
    </form>
    
    <%
        Dim Quantity
        Dim UnitPrice
        Dim TotalPrice
        Dim strCD
    
        Quantity = CInt(Request.QueryString("txtQuantity"))
    
        strCD = "CDs"
        If Quantity = 1 Then strCD = "CD"
        
        Response.Write("<p>Since you ordered " & Quantity & " " & strCD & ",<br>")
        
        If Quantity < 20 Then
    	UnitPrice = 20
        Else
    	UnitPrice = 6.25
        End If
    
        Response.Write("Each CD will cost:      " & UnitPrice & "<br>")
        TotalPrice = Quantity * UnitPrice
        Response.Write("And the total price is: " & TotalPrice & "</p>")
    %>
    
    </body>
    
    </html>
  2. Save the file
  3. Return to the browser, refresh it, enter a new value in the Quantity text box and click Calculate

The If...Then...ElseIf Statement

The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula to use is:

If Condition1 is True Then
    Statement1
ElseIf Condition2 is True Then
    Statement2
ElseIf Conditionk is True Then
    Statementk
End If

The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If.

There is still a possibility that none of the stated conditions is true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be:

If Condition1 is True Then
    Statement1
ElseIf Condition2 is True Then
    Statement2
ElseIf Conditionk is True Then
    Statementk
Else
    CatchAllStatement
End If

 

 

Practical Learning: Using If...Then...ElseIf

  1. To use If...Then...Else, change the code as follows:
      
    <%@ Language="VBScript" %>
    <html>
    
    <head>
    
    <title>CD Publisher</title>
    </head>
    
    <body>
    
    <h1>CD Publisher</h1>
    
    <form method="GET" action="cdpublisher2.asp">
      <table border="0" width="553">
        <tr>
          <td width="191">Number of CDs Ordered:</td>
          <td width="113"><input type="text" name="txtQuantity" size="10"
            value=<% =Request.QueryString("txtQuantity") %> >
          </td>
          <td width="67"><input type="submit" value="Calculate" name="btnCalculate"></td>
          <td width="162"><input type="reset" value="Start New Order" name="btnReset"></td>
        </tr>
      </table>
    </form>
    
    <%
        Dim Quantity
        Dim UnitPrice
        Dim TotalPrice
        Dim strCD
    
        Quantity = CInt(Request.QueryString("txtQuantity"))
    
        strCD = "CDs"
        If Quantity = 1 Then strCD = "CD"
        
        Response.Write("<p>Since you ordered " & Quantity & " " & strCD & ",<br>")
        
        ' The price of one CD will depend on the number ordered
        ' The more the customer orders, the lower value each
        If Quantity < 20 Then
            UnitPrice = 20
        ElseIf Quantity < 50 Then
            UnitPrice = 15
        ElseIf Quantity < 100 Then
            UnitPrice = 12
        ElseIf Quantity < 500 Then
            UnitPrice = 8
        Else
            UnitPrice = 5
        End If
    
        Response.Write("Each CD will cost:      " & UnitPrice & "<br>")
        TotalPrice = Quantity * UnitPrice
        Response.Write("And the total price is: " & TotalPrice & "</p>")
    %>
    
    </body>
    
    </html>
  2. Save the file
  3. Return to the browser, refresh it, enter a new value in the Quantity text box and click Calculate
     
  4. Return to your text editor

The Select Case Statement

If you have a large number of conditions to examine, the If...Then...Else will go through each one of them. Microsoft Visual Basic offers the alternative of jumping to the statement that applies to the state of the condition.

The formula of the Select Case is:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
End Select

The Expression will be examined and evaluated once. Then Microsoft Visual Basic will compare the result of this examination with the Expression of each case. Once it finds one that matches, it would execute the corresponding Statement.

If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The formula to use  would be:

Select Case Expression
    Case Expression1
        Statement1
    Case Expression2
        Statement2
    Case Expressionk
        Statementk
    Case Else
        Statementk
End Select
 

Loops Repeaters

 

Introduction

A loop is an expression used to repeat an action. Microsoft Visual Basic presents many variations of the loops and they combine the Do and the Loop keywords.

 

The Do...While Loop

The formula of the Do... While loop is:

Do While Condition
    Statement(s)
Loop

This expression examines the Condition. If the condition is true, then it executes the Statement or statements. After executing the statement(s), it goes back to examine the Condition. AS LONG AS the Condition is true, the Statement will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement will not be executed and the the program will move on. As you may guess already, the Condition must provide a way for it to be true and to be false.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim Counter
    
    Counter = 0

    Do While Counter <= 12
        Response.Write(Counter & " ")
        Counter = Counter + 1
    Loop
%>

</body>
</html>

This would produce:

 

The Do...Loop...While Statement

Since the Do...While statement tests the Condition first before executing the Statement, sometimes you will want the program to execute the Statement first, then go back and test the Condition. Microsoft Visual Basic offers a reverse to the formula as follows:

Do
  Statement(s)
Loop While Condition

In this case, the Statement or Statements will be executed first. Then the Condition will be tested. If the Condition is true, the program will execute the Statement again. The program will continue this examination-execution as long as the Condition is true. The big difference here is that even if the Condition is false, the program will have executed the Condition at least once.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim Counter
    
    Counter = 2.25

    Do
	Response.Write(Counter & "<br>")
        Counter = Counter + 0.35
    Loop While Counter <= 6
%>

</body>
</html>

This would produce:

 

The Do...Until...Loop Statement

An alternative to the Do...While loop is the Do...Until loop. Its formula is:

Do Until Condition
    Statement(s)
Loop

This loop will first examine the Condition, instead of examining whether the Condition is true, it will test whether the Condition is false.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim InterestRate
    InterestRate = 7.25

    Do Until InterestRate = 16
        Response.Write("Interest Rate: " & InterestRate & "%<br>")
        InterestRate = InterestRate + 0.25
    Loop
%>

</body>
</html>

This would produce:
 

 

The Do...Loop...Until Statement

An alternative to the Do...Until...loop consists of executing the the Statement first. The formula used is:

Do
    Statement(s)
Loop Until Condition

This expression executes the Statement first. After executing the Statement, it examines the Condition. If the Condition is False, then it goes back and executes the Statement again and re-check the Condition. Once the Condition becomes true, it would stop and move on; but as long as the Condition is False, the Statement would be executed.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim InterestRate
    InterestRate = 7.25

    Do
        Response.Write("Interest Rate: " & InterestRate & "%<br>")
        InterestRate = InterestRate + 0.25
    Loop Until InterestRate = 16
%>

</body>
</html>  
 

Loop Counters

 

Introduction

The looping statements we reviewed above are used when you don't know or can't anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression.

The For...To...Next Loop

 One of the loop counters you can use is For...To...Next. Its formula is:

For Counter = Start To End
  Statement(s)
Next

Used for counting, the expression begins counting at the Start point. Then it examines whether the current value (after starting to count) is greater than End. If that's the case, it then executes the Statement(s). Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until the value of Counter becomes equal to the End value. Once this condition is reached, the looping stops.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim Counter
    
    For Counter = 0 to 26
        Response.Write(Counter & " ")
    Next
%>

</body>
</html>

This would produce:

 

Stepping the Counting Loop

The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula:

For Counter = Start To End Step Increment
  Statement(s)
Next Counter

You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. This means that you can give it a negative value, in which case the Counter will be subtracted the set value.

Here is an example:

<%@ Language="VBScript" %>
<html>
<head>
<title>Active Server Pages Tutorials</title>
</head>
<body>

<%
    Dim Counter
    
    For Counter = 0 to 46 Step 2
        Response.Write(Counter & " ")
    Next
%>

</body>
</html>

This would produce:

 

For Each Item In the Loop

Since the For...Next loop is used to execute a group of statements based on the current result of the loop counting from Start to End, an alternative is to state various steps in the loop and execute a group of statements for each one of the elements in the group. This is mostly used when dealing with a collection of items.

The formula is:

For Each Element In Group
    Statement(s)
Next Element

The loop will execute the Statement(s) for each Element in the Group.


Previous Copyright © 2005-2016, FunctionX