You have spent a good bit of time up until this point hearing about variables, operators, and arrays. You have all the ingredients to start creating Active Server Pages applications, but you have yet to begin mixing them together.
In this chapter, you will be introduced to the constructs that make the variables and data interact. Sure, it's a good thing to declare a bunch of variables and operators, but without conditional processing and looping, the program will execute from left to right and top to bottom, with ability to perform different functions based upon data passed in. As you will see, it is the conditional processing and looping that provide your programs with "flow."
In this chapter you learn about:
Based upon user input and responses from external data sources, you need to take different actions within your code.
When you need to perform the same operation(s) many times, you loop.
You encounter conditional processing every day of your life. As a child, you are taught that there are consequences to your actions. The line,"if you hit your brother, you will be sent to your room," is a perfect example of a conditional process. The parent has defined a condition to test for (hitting) and an outcome based upon whether the condition has been satisfied (did you hit your brother?). This same idea of setting a condition and testing its outcome carries over into the control structures that you create for your Active Server Pages scripts.
The idea of conditional processing has an apt metaphor in the traditional flowchart. In a flowchart, you have process boxes and decision boxes. The process boxes are analogous to code blocks, and the decision boxes are analogous to If statements.
The If statement provides for conditional processing based on the outcome of an expression (or value) meeting a condition. Just like in the preceding example, you use the If statement to evaluate a condition, and based upon whether the condition is met, your code will perform some action; for example, some block of code will be executed. The following is the template for the If statement:
If (condition) Then executable code block End If
In the condition of the If statement, you will usually encounter one of the comparison operators discussed in Chapter 7, "Understanding Variable Typing, Naming, and Scoping". You can use any expression that evaluates to a numeric value as the conditional expression. If the expression evaluates to zero, the condition is considered to be not met (False). If the condition evaluates to any other numeric value, it is considered met (True), and the code within the If...End If block will be executed. Take a moment and walk through the following examples, which illustrate this point.
A user on your site has pulled up your guest book page. You want him to fill in a few informational fields so you can provide him with updated information about changes to your site. Form fields on your guest book page might include first and last name, address, and the type of computer he is using. The task you want to accomplish when you begin to process the page is to retrieve the information and then add the new user to your database. To see if he has entered his name, you check the length of the last name entry. If the length is greater than zero, the last name has been entered, and you assign the first and last name to a variable that will be inserted into your database.
If Len(strLastName) > 0 Then strName = strLastName & ", " & strFirstName InsertDatabaseRecord(strName) End If
![]()
Notice in the preceding example how the statements that are used to describe the desired functionality directly translated into the condition of the If statement. If the length of the last name (Len(strLastName)) is greater than (>) zero (0), then assign the full name to the strName variable and insert the record into the database (InsertDatabaseRecord(strName)).
If the length of the strLastName variable is greater than zero, you want to concatenate it with a comma, a space, and the first name and then assign it to the variable strName. In the preceding section, you learned that a condition, when resolved to a numeric value, is considered True if it has any value other than zero. Knowing this, you can rewrite the If statement condition without the greater-than comparison operator.
If Len(strLastName) Then strName = strLastName & ", " & strFirstName InsertDatabaseRecord(strName) End If
The two examples are equivalent because when the length of the strLastName is greater than zero, there is a value in it (sure, it might just be embedded blanks, but we'll take care of that case in a moment). Because the Len function returns the number of characters in a variable, and the If condition will be True any time the condition expression evaluates to a number not equal to zero, the condition will be met in both cases if strLastName contains a group of characters (or even one character).
![]()
When processing the length of string sub-type variables, it is recommended to remove the blank spaces before and after the string data. You can accomplish this by using the TRIM function. This will ensure that you don't mistakenly operate on a large character string of embedded blanks.
Be sure not to confuse an empty string with a variable that has not been initialized. Using the IsEmpty function, which returns a Boolean sub-type, is not the same as testing the length of a string variable by using the Len function, unless the variable has not, in fact, been initialized. Consider the following code:
Dim strOne If IsEmpty(strOne)Then 'Condition is True End If If Len(strOne) Then 'Condition is False End If strOne = "" 'assign an empty string to variable If IsEmpty(strOne)Then 'Condition is False End If If Len(strOne) Then 'Condition is still False End If
Before the strOne variable is initialized, the IsEmpty function will return True because there has not been a value assigned to strOne yet. The Len(strOne) function returns 0 or False, because the default value of a Variant variable, which has not been initialized, when used in a string context, returns "". After the strOne variable is initialized, even with an empty string, the IsEmpty function returns False.
You can have as many statements as you want within an If...End If block. If you are only going to execute one statement should the condition be met, you can put the code all on the same line and omit the End If.
If Len(Trim(strLastName)) Then strName=Trim(strLastName) & ", " & Trim(strFirstName)
This is really useful in streamlining your code when the code itself tends to document the action you are going to perform.
![]()
Remember the variable naming conventions that you learned about in Chapter 7, "Understanding Variable Typing, Naming, and Scoping." Notice that by identifying the string sub-type within the variable name (str), and the descriptive use of LastName and FirstName within the variable name, the code is self- documenting.
In this next scenario, you are creating an Active Server Pages script that processes automobile insurance applications. You have created a form and have asked your user for a variety of information. Specifically, you zero-in on one particular piece of information that you will be processing, previous-claim information. Company policy dictates that you not accept an application from an individual who has had an insurance claim within the past three years. The makings of a great conditional statement are underway!
The insurance rates you will be quoting to your applicant are based on a number of factors, but, as per your acceptance guidelines, if there has been a claim within the last three years, your applicant will not be able to apply for the insurance plan. You will want to test for this condition, and if the criteria are met (no claim within the last three years), process the application. Otherwise, you will want to generate a letter to the applicant advising her of the decision based upon her claims history.
The Else case of the If construct provides the "otherwise" processing for this scenario. Take a look at the template for the If[elThen...Else construct and then move on to our sample insurance case code.
If condition Then code to execute Else code to execute End If
If the condition evaluates to True, the first block of code between the Then and Else will be executed, otherwise, the second block of code between the Else and End If will be executed. The code for the insurance example might look something like the following:
If blnClaimLastThreeYears Then ProcessRejection Else ProcessNewApplication Endif
The Boolean variable blnClaimLastThreeYears holds the answer to the question:"Have you had an insurance claim within the last three years?" You could write the condition as blnClaimLastThreeYears = True, but this would be redundant. When a variable has a Boolean sub-type, there is no need for a comparison operator in the condition. The variable itself evaluates to True or False. As mentioned at the top of the chapter, conditional statements can be easily derived directly from a flowchart, as the insurance scenario is illustrated in Figure 8.1.
Notice how easily If, Then, Else constructs flow from the flowchart.
You will encounter many cases as you continue to develop your applications in which you will want to evaluate multiple criteria in the condition of an if statement. Using logical operators is the key to evaluating multiple criteria in a condition. Through the use of truth tables, as outlined in Table 8.1, you can see what the results of evaluating a logical condition will be.
Table 8.1 The AND Truth Table
First Condition | Second Condition | Outcome |
True | True | True |
True | False | False |
False | False | False |
False | False | False |
In the earlier example in which you were processing a guest page, you were testing the length of a LastName variable and then appending the FirstName to put the whole name into a variable for insertion into a database. In that example, you assumed that if the LastName were entered, so was the FirstName. Now, I don't need to tell you what happens when you assume.... If the First Name were not entered, or were left blank, the previous sample code would continue to process. Now you'll update the code to ensure that both the first and last names are entered.
If Len(Trim(strLastName)) AND Len(Trim(strFirstName)) Then strName = Trim(strLastName) & ", " & Trim(strFirstName) InsertDatabaseRecord(strName) Else ReturnInvalidNameError End If
The logical AND operator is used to ensure both names have at least one character in them. If either variable evaluates to an empty string, you will return an error code to the client.
In other cases, you would want the condition to be satisfied if either one of the variables had a character in it. In that case you would use the logical OR. The truth table for the logical OR operator is found in Table 8.2.
Table 8.2 The OR Truth Table
First Condition | Second Condition | Outcome |
True | True | True |
True | False | True |
False | True | True |
False | False | False |
In the following example, the script determines the region of the guest book user by evaluating the state passed in from the client.
If strState = "CA" OR strState = "AZ" Then strRegion = "Pacific" End If
Within the code, you are accepting California or Arizona to meet the condition of a Pacific-region state. This is certainly not the best way to determine a region from a state, but it gets the logical OR point across. A match on either of the states will cause the condition to be met, and the code block within will be executed.
You can also use the negation logical operator to good effect in your If statement conditions. Sometimes, it just makes the code more readable to use the NOT operator. Table 8.3 shows the truth table for the logical NOT.
Table 8.3 The Not Truth Table
First Condition | Second Condition | Outcome |
Not | True | False |
Not | False | True |
Now, you can take a look at a few additional examples to illustrate the outcomes of using and then combining these logical operators within conditional statements:
If blnActiveAccount AND intYears >= 5 Then ProcessNomination End If
In the preceding example, you are using the logical AND to determine whether to process the nomination of a hypothetical member of some group. When creating conditional statements, it is usually written exactly as it sounds. For example, you will process a nomination if the member is active and has been with you for at least 5 years. You can see the logical AND within the declaration. Use of the logical OR will follow along the same lines. The following code illustrates this type of declaration: If the account holder is the primary or secondary borrower on the note, release the account information, otherwise, notify them of the restrictions on disclosure.
If (strRequestor = "primaryBorrower" OR strRequestor = "secondaryBorrower") Then ReleaseLoanData Else ReturnDisclosureNotification End If
You can create very complex logical conditions for use with the If statement by combining multiple logical operators in the condition.
If (intDays > 5 AND lngMiles < 1000) OR (blnActive AND NOT blnDeceased) Then ProcessReimbursement Endif
The expression in the preceding If statement is evaluated just like any other compound expression, each expression is evaluated within the parentheses groups, and then logically OR'd (in this example) together. Ultimately, the condition evaluates to zero (False) or any other numeric value (True).
Implementing Nested If Statements
Nested If statements provide you with an added level of functionality when developing applications that require multiple levels of conditional testing. The nesting refers to the embedding of conditional If blocks within other If blocks. As you traverse through the nested levels, the inner If condition is evaluated only if the outer condition is met. The template for nested If statements looks like this:
If condition Then 'Top level If condition Then '1st Nested Level If condition Then '2nd Nested level End If End If End If
The template can be expanded to include up to 8 levels of nesting. Each nested level can also include the Else case, which can in turn contain its own nesting.
One of the most useful things that you will use Nested If processing for is data validation. Within your Active Server Pages applications, you want to ensure that all user-entered data coming in to your script is valid before processing it. Using Nested If statements provides you with another great tool to use when performing data validation. To begin the discussion, our nesting scenario concentrates on validating the Date sub-type variable.
Dates are a major source of input data that are used in most business queries. Management needs to know what the value of the key indicators of your business are, but they must be evaluated within a specific context to have meaning: their value today, month to date, or year to date. Your users will want to see data for a given date range. They also might request a summary of information from a given date to the present date. The use of dates in your business applications are so prevalent, that it is worthwhile to discuss them now in a data-validation context.
When accepting input from a user, you want to ensure that any calculations you perform using a date passed to you is, in fact, a valid date. This will ensure that you can provide accurate information back to the client.
There are a few different levels of validation that you will want to perform for a given date value. At the lowest level, you want to ensure that the date variable contains valid data. This means the input data string will resolve to a date value. A variable with an invalid date might contain something like XXNNMYYZZZZ. Try to get a date value out of that string! The next level of "valid-ness" would be based on the context in which you will be using the date value. For a given context, you might restrict the date based on a date range of the data available. Any date outside this range would be considered invalid in this context. A valid date might also be restricted to be greater than today's date or some other range that you create to define a "valid date" for your particular context.
To check these multiple levels of validity, you use Nested If statements. At each of the nested levels, you will perform a date validation step. If the condition specified is met and the date is validated, you will proceed to the next level of nesting and the next level of date validation. Just remember that as you increase the number of levels, you increase the likelihood of errors within the nested block. The following code shows you date validation using Nested If statements.
If IsDate(dteInput) Then If DateValue(dteInput) < Date Then ReturnDateRangeError Else ProcessDataRequest Endif Else ReturnInvalidDate End If
The first line of code ensures the variable dteInput contains a value that can be resolved to a date. The IsDate function resolves an expression to a date value. If the expression passed to the function can be resolved, it returns True. If the value cannot be resolved to a date, the function will return False. The wonderful thing about the IsDate function is that it will not generate a run-time error regardless of what you pass into it.
If the first condition is met, IsDate(dteInput) you now move on to the 'next level' of nesting, verifying the validity of the date value in our context. The second test ensures that the now "verified" dteInput date is greater than the current date. The Date function returns the current system date. The DateValue function returns a date representation of the expression passed into it. If this second level of date verification passes, the request will be processed.
![]()
Whenever you are performing operations that use dates, like the DateValue function in the prvious example, you always want to test to ensure the expression or variable can be resolved to a date by using the IsDate function. If you pass an expression to the DateValue function that cannot be resolved to a date, the code will generate a run-time error. You will always want to code to avoid possible run-time errors. That is called defensive programming, and it is one of the differences between a mediocre and a professional developer.
Nesting If statements are ideal when you want to test conditions against different variables at different levels. If you are setting up conditions for the same variable at each of the nesting levels, you are setting up a nested Tandem If.
When you want to take an action based upon the value of a variable, you use the If statement. You set up a condition that, if it evaluates to True, processes a block of code. There are many times that you will find yourself writing multiple If statements to check for a finite range of values within a single variable or expression.
In the next example, we are going to generate a custom response based upon the prefix of our user's name. It has a limited set of values (Ms, Dr, and so on) that you will test for. If one value is met, you can be sure that none of the other If conditions will be met because you are testing the same variable again and again.
If strNamePrefix = "Mr." Then code here End If If strNamePrefix = "Ms." Then code here End If If strNamePrefix = "Dr." Then code here End If
The type of code section just shown is referred to as Tandem If statements. The statements work together to take an action based on the various types of data that the strNamePrefix variable will hold. Notice that each of the conditions in the preceding code are mutually exclusive. There are no duplicate conditions. This ensures that only one prefix response will be sent back to your user. The problem with this type of code is that without using a flag in each If block, you will be hard-pressed to provide a default value for the case where none of the conditions are met. You can provide a default value by combining the Tandem If with the nested If...Then...Else...If code blocks.
If strNamePrefix = "Mr." Then code here Else If strNamePrefix = "Ms." Then code here Else If strNamePrefix = "Dr." Then code here Else default action here End If End If End If
The nesting allows you to have a default action when none of the explicit conditions are met. As the number of possible values that strNamePrefix can hold increases, the level of nesting increases as well.
There is one last format for nesting of the If statement that provides the same functionality that you see in the last example. It just pushes the Else and If together to look more like this:
If strNamePrefix = "Mr." Then code here ElseIf strNamePrefix = "Ms." Then code here ElseIf strNamePrefix = "Dr." Then code here Else default action here End If
This new format eliminates the need to explicitly close each If block with an End If. While greatly improving the look of the nested code, deep nesting in general can get ugly very, very quickly. I have had to work with programs over the years that have come to be known as "Nested If From Hell" programs. These programs (actually written in C, but I'm sure there are some out there in VB and other higher level languages) have an If at the top of the module and an End If (or closing brace) at the bottom. In between, there are levels upon levels of nested Ifs. The complexity of the code is in direct proportion to its level of nesting. The more nesting levels, the greater complexity within the code. To avoid the temptation of the nested Ifs in these situations, the Select Case statement provides the same functionality in a much easier to understand and user friendly format.
As you saw in the preceding section, the Tandem If provides you with a framework for taking actions based upon a set number of known outcomes for a variable or an expression. The same functionality is found within the Select Case statement but in a much more elegant form. Here is the template for the Select Case statement:
Select Case testexpression [Case expressionlist-n [statements-n]] . . . [Case Else expressionlist-n [elsestatements-n]] End Select
The first line sets up the condition or case that will be tested. The body of the Select Case statement contains the cases that you want to test for. Each of the Case expressionlist(s) have values that, when equal to the test expression, are considered met.
The test expression is any valid VBScript expression. It is evaluated and then compared to the values in the expression list in the Case statements under the Select. If the test expression value matches one of these expression list items, the code within that Case statement will be executed. If the test expression does not match any of the items in any of the Case statements, the code block under the Case Else statement is executed. The Case Else block is also referred to as the default case.
You must have at least one Case statement in the body of a Select statement. The Case Else statement is not required, although in most cases you will want to specify a default action. If there is no default action and none of the Case expression lists are met, the entire Select statement is bypassed. Look at the Tandem If example from the previous section as constructed with the Select Case statement:
Select Case strPrefixName Case "Mr." Case "Mrs." Case "Dr." Case Else End Select
The Select is a much better construct to use for this type of processing. It is easier to read and easier to implement. And you don't have to worry about having mismatched If...End If pairs in a huge nested mess. Now, there are situations where nested Ifs are the best solution to a programming challenge. With a little forethought, you can ensure that you use the right conditional process for each situation.
The Select Case statement is very flexible with regard to what you can put in the expression list. Often, you will need to have a range of values in the expression list. Take, for example, the case of determining benefits status for an employee based upon the time employed.
Select Case intYearsEmployed Case 0 to 1 strMessage = "Benefits will be available on the first anniversary with the company" Case 1 to 4 strMessage = "Your pension will be fully vested after year 5." Case 5 to 9 strMessage = "You are now elligible for 3 weeks of vacation" Case Else strMessage = "You have been here a long time!" End Select
The level of benefits that an employee is eligible for is determined by her continuity of service, or how long she has been with the company. Using the Select Case construct, it is very easy to construct custom messages based upon an employee's years of service. Anytime you want to take actions based upon a range of values for a variable, the Select Case is the construct to use.
In addition to specifying a range in the expression list, you can have multiple values within the expression list to provide additional options for hitting the case (matching the test condition). You can mix and match ranges and values to get the desired effect.
Select Case intLuckyNumbers Case 1 to 3, 7 Case 4 to 6 Case 9, 11 Case 8, 12 Case Else End Select
One of the most useful places to use a Select Case statement is in processing error codes and returning custom messages to your user based upon the error code encountered at the back-end service.
Select Case sqlError Case 1024 'Insert Failed, Row Already Exists strCustomMsg = "Can not insert your record into the database. " & _ "The record already exists" Case 2001 'Insert Failed, Invalid Row Data strCustomMsg = "Insert failed. There was invalid input data" Case Else strCustomMsg = "Sql Error processing insert: " & sqlError End Select
As you get into Chapter 9, "Calling Procedures: Functions and Subroutines," you will be constructing functions that make full use of the Select Case construct's many useful features.
Looping is one of the most powerful processing constructs available. Programming loops provide your programs with the ability to execute the same block of code over and over again, until a predefined condition is met.
To understand looping, you need only take a look at any number of activities that you perform throughout the year. Take a moment to try to remember the last time that you planted a tree (or a bush, anything that you had to dig a hole to plant). Based on the type of plant and its size, you determine the size of the hole that you need to dig. You pick up your shovel and begin. You put the shovel in the dirt, kick it down, and throw the dirt to the side. Are you done yet? No? You start to dig again, and after each shovelful of dirt, you determine whether the hole is large enough. If not, you continue to dig. If it is, you plant your tree and go on to some other essential task, like cutting the grass or napping. The workflow of this planting process is shown in Figure 8.2.
Examples of Looping are found everywhere.
This outdoor planting exercise is a perfect example of how a loop works. You know you have to meet some predetermined criteria (a hole of a certain size). You have a block of work to perform (dig a shovelful of dirt each time) that will ultimately fulfill the requirement, but you are not sure how many times you will have to perform the work until the criteria is met. Then, you go ahead and perform the block of work until the condition is met. As you will see, constructing loops programmatically is implementing that same repetitive functionality in your code.
The Do Loop construct is one of the looping methods with which you can perform multiple executions of a block of code within your Active Server Pages scripts. The template for the Do loop is:
Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop
Notice that the test to see if the condition is met is performed before the code within the loop is ever executed. In this case, the statements within the loop will be executed 0, 1, or more times. There are, however, a number of situations in which you want to ensure the code within the loop is executed at least once. To add this functionality, we move the test for the condition to the "bottom" of the loop, and now have the second form of the Do loop.
Do [statements] [Exit Do] [statements] Loop [{While | Until} condition]
In this form of the Do loop, the loop will be executed at least one time. This is an important distinction. Where you place the condition determines if and when the code within the loop is executed.
Don't let the While/Until confuse you. They are just two ways of expressing the same functionality. Which one you use will be determined by which "sounds" better. Because you usually code from pseudo code that was generated from business requirements, you select the one that expresses the condition best.
Do While intValue < 4
is functionally equivalent to
Do Until intValue > 3
The form of the Do loop (testing at the top or bottom) that you choose will be determined solely on whether you want to ensure the loop executes at least one time. Other than where the condition is tested, at the top or bottom of the loop, the two forms are functionally equivalent.
As your script merrily goes on its way executing the code within the loop, there will surely come a time in which you want to immediately exit from the loop. If you find this out at the bottom of the loop, you could just put a condition killer (a value that satisfies the condition, exiting the loop) into the variable that you are checking. This is not the best solution, and no solution at all if you are somewhere in the middle of the loop when you determine that you need to exit. To exit the loop at any time within the loop code block (before meeting the condition that causes the loop to end), use the Exit Do statement. This immediately causes the processing within the loop to stop.
You can also nest Do loops. The Exit Do statement will transfer control to the loop that is one level above the current nested loop. If the loop is not nested, or if you are in the top-most nested loop, the Exit Do statement returns control to the first statement immediately after the loop. Take a look at an example of nesting loops and the Exit Do statement.
Dim intCounter1, intCounter2 intCounter1 = 0 Do While intCounter1 < 10 intCounter2 = 0 Do intCounter2 = intCounter2 + 1 If intCounter2 = intCounter1 * 2 Then Exit Do End If Loop While intCounter2 < 10 intCounter1 = intCounter1 + 1 Loop
In the preceding example, the value of intCounter2 gets up to nine only five times. Notice the Exit Do in the nested loop will exit the inner loop but will not exit the outer one. After the outer loop is completed, intCounter1 will have a value of 10.
You will find there are situations when you want to start processing in a loop and never exit. The loop will not end until an error condition is raised or some internal flag is set to exit the loop. To set up this type of loop, you use True as the condition of the statement.
Do While True GetUserInput If blnError Then Exit Do End If Loop
In the preceding example, the code continues to execute until the blnError flag is set to True. This "endless loop," as it is more commonly known, is not a favorable occurrence in most cases. If you did not explicitly intend for the loop to execute forever, and it does, you have a problem that needs to be addressed.
The While construct is a construct that is much like the Do...Loop construct. Its template follows:
While condition [statements] Wend
This is functionally equivalent to the first form of the Do loop that was discussed previously. The major difference is the absence of an Exit While statement to leave the loop before the condition is met. The option of using Until in the condition is also lacking.
In the next example, you want to find out how many occurrences of the word "the" are in a text area passed back to us from a form. You can use the While...Wend construct to facilitate this activity.
Dim strTextArea, strSearch, intPosition, intOccurrences intPosition = 1 intOccurrences = 0 strSearch = "the" While InStr(intPosition, strTextArea, strSearch) intOccurrences = intOccurrences + 1 IntPosition = InStr(intPosition, strTextArea, strSearch) + 1 Wend
You are using the InStr function, which returns the position of one string within another as your condition. A While condition is evaluated just like the condition of an If statement. If the expression evaluates to a numeric value, any value other than 0, the condition will be considered met or True. The InStr function returns 0 if the search string is not found. The intPosition is the position from within the target string to start the search. The While works well in this case because you do not need to exit the loop until the entire string is searched, nor will you have to execute the loop at least once. Either the condition is met (an occurrence found) or not.
In general practice, it is better to use the Do Loop construct than the While...Wend. The Do loop is much more flexible and provides a number of additional features that are not available in the While...Wend loop. You will encounter this construct if you are converting from older code or adapting older VB code to be used by your Active Server Pages scripts.
The For...Next loop provides much of the functionality of the Do loop but with an important difference: you know before you enter the loop how many times you want to execute the code within the loop. The For...Next loop template is shown as follows:
For counter = start To end [Step step] [statements] [Exit For] [statements] Next
The counter is initialized to the value in start and then incremented by step each time through the loop. If not ended prematurely, the loop will stop executing when the counter is greater than the end value. The counter is incremented at the bottom of the loop. The For loop also has an easy exit-the-loop statement, Exit For, which will break out of the loop regardless of the status of the condition, just like the Exit Do in the Do loop.
The power inherent in the For Next Loop construct is demonstrated by creating a function to perform the calculation of a factorial. Factorials are mathematical calculations that multiply a value by each integer value less than the number you are computing the factorial for. For example, the factorial for !4 would be 24 (4 * 3 * 2 * 1). I know this is a bit premature, but you will now see a function to compute the factorial of a number, just a quick taste of what to expect in Chapter 9, "Calling Procedures: Functions and Subroutines."
Function ComputeFactorial(n) dim intCounter, intFactorial intFactorial = CInt(n) For intCounter = CInt(n) - 1 To 1 step -1 intFactorial = intCounter * intFactorial Next ComputeFactorial = intFactorial End Function
The ComputeFactorial function calculates the factorial of the number passed in. We know ahead of time that we want to loop for n - 1 times to calculate the factorial. When the step is not explicitly stated, it defaults to 1. You can also have a negative value as the step value to decrement a counter over a given range. We could have written this code using a Do loop, or even a While loop, but the For loop is the best construct to use when you know the number of iterations you will be executing in advance.
One of the things that you will be using the For loop for is array processing. You can loop through the members of an array in no time using the For loop. Say that you have an array of names that define a set of active members of some group. You are now going to verify that a new user coming in to your site is a member of this list. You are going to fill an array of all the valid members from a database.
Dim memberArr(10), intIterator Code to load memberArr from database or flat file blnMember = False For intIterator = 0 to Ubound(memberArr) If strUser = memberArr(intIterator) Then blnMember = True Exit For 'We have verified the user, exit the loop End If Next
In reality, you would likely just query the database each time to verify the new user. It is possible that you could maintain a small list of users in a flat file and read that into an array to verify users, as well. Anyway, you use the For loop to walk the array from 0 to its upper bound. You then use a conditional If statement to see if the username that was passed in matches any of the names in the array. If they do, you set the member flag to True and immediately exit the loop using the Exit For statement.
You have looked at a number of programming constructs that allow you to make decisions and perform operations on your data. Without the ability to process conditional statements or to perform looping in your code, you would be reduced to code each revolution of the loop individually. How would you like to spin through a 100-item array and have to create a new line of code for each array element!
You are headed toward the end of section 2. Here is how you will be integrating what you have learned so far:
© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.