Active Server Pages/Conditionals and Looping
Objectives
[edit | edit source]In this section we will introduce the basic program flow-control statements available to you in Active Server Pages. This includes conditional statement and looping constructs. After studying this section, you should have a good understanding of how to use Active Server Pages to make decisions based on expressions. You should also understand how to repeat a block of program code based on conditions you define.
Content
[edit | edit source]Conditional statements are used by your program to make decisions and decide what the program should do next. An example of this would be deciding whether a user has entered the correct password for your site by comparing the password entered with the correct password. If the user passes the test, they are sent to their account management Web page. If they fail, they are sent back to the login screen with an error indicating the "password is invalid".
This kind of decision making is common in all programming languages. You need to master this aspect of Active Server Pages in order to write dynamic web applications.
Another important concept is looping. Looping simply means that you repeat the same block of code multiple times. Since you are going through the code once, going back to the beginning and repeating it again, the direction of program execution looks like a loop (or a circle) which is why we call it looping. We will introduce you to all of the looping methods available to you in this chapter.
Program Flow
[edit | edit source]In general, program flow starts at the very top of the page and continues all the way down the page in the same way that you read a book. All pages are executed this way in ASP and it makes the code very easy to follow until you get to conditional statements and looping constructs.
Because of the logical flow of the program, it is easy to trace through your program code and output debugging information to see what your script is doing as it gets processed by the ASP interpreter. Through use of the Response.End statement, you can place breakpoints in your script to stop execution at specific points. More about this will be discussed later.
One topic that will not be covered in this section is procedure and object method calls. We will talk about these in later sections.
Conditionals
[edit | edit source]A conditional statement is one where an expression is evaluated and based on the result one or more actions may be taken. This allows you to check for a certain condition and take a specific action that is required when the condition is or is not met.
If-Then Statement
[edit | edit source]The "If-Then" statement is the most basic conditional statement. When put on a single line, this statement says "If the condition is met, then do this." For example, we could test to see if someone is old enough to vote with:
If nAge > 18 Then Response.Write "Yes, you can vote!"
You may optionally, create an If-Then statement that encloses a block of statements. A block of statements means more than one statement grouped together. In this case, the entire block of statements will be executed only when the condition is met. We use indenting in this case to help us read the code and determine where the block starts and ends.
If nAge > 18 Then
Response.Write "Yes, you can vote!"
bCanVote = true
End If
As you can see in this program block, the If Then statement defines the start of the program block while the End If statement defines the end of the program block. The program block is indented to make it easier to match the start and end of the block. All of the statements in this program block will only be executed if the conditional statement is met (nAge > 18). When it is not, nothing will be done.
If-Then-Else
[edit | edit source]The If Then statement is great, but what if you want to perform two different actions. One action to be taken when the condition is met and one action to be taken when the condition is not met. That is what the If Then Else statement was create to handle. It basically says: "If the condition is met, then do this, otherwise do this".
If nAge > 18 Then bCanVote = true Else bCanVote = False
As you can see from the example above, you can put the entire If Then Else statement in one line. In many cases, you will want to avoid this since it tends to make the length of the line very long. Instead, you will probably want to use the program block form like so:
If nAge > 18 Then
Response.Write "Yes, you can vote!"
bCanVote = true
Else
Response.Write "No, you can not vote."
bCanVote = false
End If
In this case, only one of the two program blocks will be executed. The first will be executed when the condition is met. The second will be executed when the condition is not met. So you can think of the If Then Else statement as saying "one or the other but not both".
Although we are using more than one statement in the program blocks shown above, you could also put a single statement within each program block. For debugging purposes, you can even have no statements at all within a program block. This allows you to comment out all the statements in a program block and your script will still run no problem.
You will notice that in the conditional expression for the If Then statement, we did not have to enclose the condition with parentheses "(" and ")". You can always use parentheses for grouping expressions together but they are not required to enclose conditional statements.
Select Case
[edit | edit source]The If Then statements are great if you are just evaluating a "true" or "false" condition. But if you want to evaluate an expression other than a boolean and take some action based on the result, you will need another mechanism. This is why the ASP language includes the Select Case statement. This allows you to basically "select" from a list of many cases, the action to perform.
The cases for a Select Case are all literal primitive values. You must have an "exact match" in order to match a "case". You may include more than one value to match, but you may not define ranges of values to match, nor may you define a pattern to match.
Select Case nAge
Case 15, 16
Response.Write "You are almost old enough to vote"
Case 17
Response.Write "You might want to register to vote"
Case 18
Response.Write "Yes, you can vote!"
Case Default
Response.Write "Catch-all for all other ages"
End Select
This select statement is a little deceiving, because it will only tell you that you can vote if the age is 18 and only 18. If the age is greater than 18, then none of the specific cases will be matched. Instead, the optional catch-all case (Case Default) will be executed when the age is greater than 18.
Of course, you don't need to include the Case Default if you don't need it. By leaving it off, you are basically saying "do nothing if an exact match for a case is not found".
You can use any expression for the Select Case as long as it evaluates to a primitive type. You can not use an object expression because there is no such thing as an object literal to compare it to. However, you can call an object method that returns a primitive type and use this as the expression.
In the example shown above, you can see that we are using the carriage return to separate the Case from the block to be executed. There is no need to terminate this type of program block. It is terminated by the instance of the next case or the End Select. You may also put the case and the action to perform on the same line by using the colon (:) as a statement separator:
Select Case nAge
Case 15, 16 : Response.Write "You are almost old enough to vote"
Case 17 : Response.Write "You might want to register to vote"
Case 18 : Response.Write "Yes, you can vote!"
Case Default : Response.Write "Catch-all for all other ages"
End Select
Looping Constructs
[edit | edit source]Looping constructs are used for repeating the same step over-and-over again. There may be many reasons to use a loop. In database-driven web applications, you will often use a loop to iterate over each record returned from a recordset.
For Next Loop
[edit | edit source]The "for next" loop allows you to repeat a block of code using an incremental counter. The counter is initialized at the start of the loop and then incremented at the end of the loop. At the start of each repetition, the counter is checked to see if it has exceeded the ending value. This is best explained by using an example:
For I = 1 To 10
Response.Write "I = " & I & "<br>"
Next
In this example, we have created a loop that is repeated 10 times. We know it executes exactly ten times because you can read the statement as "for every whole integer from 1 to 10, do this".
The variable "I" is initialized with a value of 1 and the first repetition of the program block (indented) is executed. The output will be "I = 1". Don't worry about the "<br>" part, this is just HTML code to create a line break on the web page.
The second time through the loop, the counter (I) is incremented and takes on a value of 2. So the second line output by this block is "I = 2". This process repeats as I is incremented one at a time until the counter exceeds the end value. So in this case, the last line printed will be "I = 10".
In a more advanced case, we can change the way in which the index is incremented. If we wanted the counter to increment by 2, we would write the For Next loop as follows:
For I = 1 To 10 Step 2
Response.Write "I = " & I & "<br>"
Next
The output of this code will be:
I = 1 I = 3 I = 5 I = 7 I = 9
This time we only get five values output by the loop. This is because we are incrementing the counter by 2 instead of by 1 (the default.) Notice that we do not have to finish on the ending value (10). After incrementing the counter from 9 to 11, the loop checks to see if we have exceeded the ending value (10) and exits the loop.
You can also count backwards like this:
For I = 10 To 1 Step -1
Response.Write "I = " & I & "<br>"
Next
And of course, you can substitute expressions and variables for the starting and ending values and even the amount to "step through" the loop:
For I = nX + nY To YourFunc(nZ) Step nStep
Response.Write "I = " & I & "<br>"
Next
Do While
[edit | edit source]Another looping construct is the Do While loop which will repeat a block of program code as long as the condition is met. This is kind of like the If Then conditional statement in that it expects a boolean expression. Here is what it looks like:
I = 1
bFound = False
Do While I < 10
Response.Write "I = " & I & "<br>"
I = I + 1
Loop
What we have here is a loop that does exactly the same thing as the For Next example shown in the previous section. Why would you want to use this construct instead of a "for next"? The problem becomes obvious when it is not easy to determine how many repetitions of the loop you need to do.
X = 239821.33
Do While X > 1
Response.Write "X = " & X & "<br>"
X = X / 2
Loop
In this case, we do not know how many times we will have to divide the value of X by two until we end up with a value less than or equal to 1. So we just use the Do While loop to handle the logic for us.
Do Until
[edit | edit source]Almost identical to the Do While looping construct is the Do Until. It works exactly the same way except that it repeats the program block until the condition evaluates to "true". You could basically do the same thing with "Do While" by enclosing your expression with Not (expr), but the creators of ASP realized that the code would be cleaner using this more logical statement.
X = 239821.33
Do Until X <= 1
Response.Write "X = " & X & "<br>"
X = X / 2
Loop
Here, we have created a loop that does exactly the same thing as our "do while". We just reversed the logic of the conditional statement and changed the keywords to Do Until. In this case, it doesn't make the code that much cleaner to read. But as we will see later, there are definite cases where you will want to use Do Until.
While
[edit | edit source]The While loop works exactly the same as the Do While except that it has a little shorter construct. Please read the section on "Do While" to understand how this looping construct works.
X = 239821.33
While X > 1
Response.Write "X = " & X & "<br>"
X = X / 2
Wend
Unlike the "Do" loops, the While loop program block is terminated by the Wend statement.
Summary
[edit | edit source]Active Server Pages has many different control flow statements to handle the execution of your ASP page. The conditional statements are: If Then, If Then Else and Select Case. The looping constructs are For Next, Do While, Do Until and While. Conditional expressions in ASP do not need to be enclosed in parentheses ("(" and ")").
For Next loops manipulate a counter and repeat the program block until the counter exceeds the ending value. Do While, Do Until and While loops repeat based on the evaluation of a boolean expression (meaning an expression resulting in the value of "true" or "false").
Review Questions
[edit | edit source]- What types of conditional statements are available in ASP?
- What types of looping constructs are available in ASP?
- What are the three parameters for a For Next loop.
- How do you count backwards using a For Next loop.
- What loop would you use to repeat until a condition is satisfied?
- What loop would you use to repeat while a condition is satisfied?
- How do you terminate a program block for a Do While loop?
- How do you terminate a program block for a While loop?
Exercises
[edit | edit source]- Create a For Next loop that outputs integers from 10 to 100 that are evenly divisible by 10