VBScript Conditional Logic

Home  »  ASP  »  VBScript Conditional Logic



What Is a Control Structure?

There are three major types of control structure that programmers use. They allow control over if, when, and how many times certain instructions are executed. Mastering the use of these control structures is critical to becoming skilled as a programmer.




Conditional Logic

Conditional logic tests a condition or a series of conditions and, based on the result, chooses what code should be executed.

If...Then Statements

The If...Then statement is one of the most commonly used control structure. It takes the form.

If condition Then
   code block
End If

condition is a Boolean expression, When condition evaluates to True, the action statements are carried out, and the whatever comes after End If is carried out. If condition evaluates to False., the action statements are skipped and only what comes after End If carried out.

Example: 1 First Version of the Grade Finding Code




If...Then...Else Statements

Sometimes it is useful to have a segment of code that executes only if the condition fails. You can add an else statement to the if...then structure.

If condition Then
   code block 1
Else
   code block 2
End If

Now if condition evaluates to True, code block 1 is executed. If it evaluates to False, code block 2 is executed.

Example: 2 If...Then Statement




ElseIf Statement

The ElseIf statement simplifies one common type of nested If structure. An If statement that looks like this:

If condition Then
   code block 1
Else
  If condition Then
     code block 2...

can be changed to this:

If condition Then
   code block 1
ElseIf condition2 Then    code block 2...

The ElseIf functions as a combined If and Else. Bear in mind two things when you are using ElseIf.

  1. ElseIf may not appear after an Else. You can use repeated ElseIf statements, followed by an Else if you want, but no ElseIf statement may follow an Else.
  2. ElseIf does not require and End If of itw own, but the original If still does.
Example: 3 ElseIf Statement




Select Case Statements

Even with the addition of the ElseIf, it can still be unwiedly to use nested If statements if you are going more than two or three levels deep. You have probably used a keystroke-driven program before, where choosing "A" would cause one thing to happen, "B" something else, and so on.

This is why the Select Case statement is aviable. Select Case allows you to specify a sequence of code blocks, one of which will be carried out depending on the value of a numerical or string expression. The syntax looks like this.

Select Case expression
Case value1
  Code for when expression equals value1
Case value2
  Code for when expression equals value2
...
Case valueN
  Code for when expression equals valueN
End Select
Example: 4 Select Case Statements








Share on Google Plus
    Blogger Comment
    Facebook Comment