Writing For Next Loops


Writing For…Next Loops

With a For…Next loop, you can execute a specific group of program statements a set number of times in an event procedure or a code module. This approach can be useful if you're performing several related calculations, working with elements on the screen, or processing several pieces of user input. A For…Next loop is really just a shorthand way of writing out a long list of program statements. Because each group of statements in such a list does essentially the same thing, you can define just one group of statements and request that it be executed as many times as you want.

The syntax for a For…Next loop looks like this:

For variable = start To end      statements to be repeated Next [variable]

In this syntax statement, For, To, and Next are required keywords, as is the equal to operator (=). You replace variable with the name of a numeric variable that keeps track of the current loop count (the variable after Next is optional), and you replace start and end with numeric values representing the starting and stopping points for the loop. (Note that you must declare variable before it's used in the For…Next statement.) The line or lines between the For and Next statements are the instructions that are repeated each time the loop is executed.

For example, the following For…Next loop sounds four beeps in rapid succession from the computer's speaker (although the result might be difficult to hear):

Dim i As Integer  For i = 1 To 4      Beep()  Next i

This loop is the functional equivalent of writing the Beep statement four times in a procedure. The compiler treats it the same as

Beep()  Beep()  Beep()  Beep()

The variable used in the loop is i, a single letter that, by convention, stands for the first integer counter in a For…Next loop and is declared as an Integer type. Each time the loop is executed, the counter variable is incremented by one. (The first time through the loop, the variable contains a value of 1, the value of start; the last time through, it contains a value of 4, the value of end.) As you'll see in the following examples, you can use this counter variable to great advantage in your loops.

Displaying a Counter Variable in a TextBox Control

A counter variable is just like any other variable in an event procedure. It can be assigned to properties, used in calculations, or displayed in a program. One of the practical uses for a counter variable is to display output in a TextBox control. You used the TextBox control earlier in this book to display a single line of output, but in this chapter, you'll display many lines of text by using a TextBox control. The trick to displaying more than one line is simply to set the Multiline property of the TextBox control to True and to set the ScrollBars property to Vertical. Using these simple settings, the one-line text box object becomes a multiline text box object with scroll bars for easy access.

Display information by using a For…Next loop

  1. Start Visual Studio, and create a new Visual Basic Windows Application project named My For Loop.

    A blank form appears in the Designer. Your first programming step is to add a Button control to the form, but this time you'll do it in a new way.

  2. Double-click the Button control in the Toolbox.

    Visual Studio places a button object in the upper-left corner of the form. With the Button control and many others, double-clicking is a quick way to create a standard-sized object on the form. Now you can drag the button object where you want it and customize it with property settings.

  3. Drag the button object to the right, and center it near the top of the form.

  4. Open the Properties window, and then set the Text property of the button to “Loop”.

  5. Double-click the TextBox control in the Toolbox.

    Visual Studio creates a small text box object on the form.

  6. Set the Multiline property of the text box object to True, and then set the ScrollBars property of the text box object to Vertical.

    These settings prepare the text box for displaying more than one line of text.

  7. Move the text box below the button, and enlarge it so that it takes up two-thirds of the form.

  8. Double-click the Loop button on the form.

    The Button1_Click event procedure appears in the Code Editor.

  9. Type the following program statements in the procedure:

    Dim i As Integer  Dim Wrap As String  Wrap = Chr(13) & Chr(10)  For i = 1 To 10      TextBox1.Text = TextBox1.Text & "Line " & i & Wrap  Next i

    This event procedure declares two variables, one of type Integer (i) and one of type String (Wrap). It then assigns a string value representing the carriage return character to the second variable.

    TIP
    In programmer terms, a carriage return character is the equivalent of pressing the Enter key on the keyboard. I created a special variable for this character in the program code, which is made up of return and linefeed elements, to make coding a carriage return less cumbersome. The return element, Chr(13) moves the I-beam to the beginning of the line. The linefeed element, Chr(10), reminiscent of an older style typewriter, moves the I-beam to the next line.

    After the variable declaration and assignment, I use a For…Next loop to display Line X 10 times in the text box object, where X is the current value of the counter variable (in other words, Line 1 through Line 10). The string concatenation characters (&) join together the component parts of each line in the text box. First, the entire value of the text box, which is stored in the Text property, is added to the object so that previous lines aren't discarded when new ones are added. Next, the “Line” string, the current line number, and the carriage return character (Wrap) are combined to display a new line and move the I-beam to the left margin and down one line. The Next statement completes the loop.

    Note that Visual Studio automatically adds the Next statement to the bottom of the loop when you type For to begin the loop. In this case, I edited the Next statement to include the i variable name—this is an optional syntax clarification that I like to use. (The variable name makes it clear which variable is being updated, especially in nested For…Next loops.)

  10. Click the Save All button on the Standard toolbar to save your changes, and specify the c:\vb05sbs\chap07 folder as the location.

    Now you're ready to run the program.

    TIP
    The complete For Loop program is available in the c:\vb05sbs\chap07\for loop folder.

  11. Click the Start Debugging button on the Standard toolbar.

  12. Click the Loop button.

    The For…Next loop displays 10 lines in the text box, as shown here:

    graphic

  13. Click the Loop button again.

    The For…Next loop displays another 10 lines on the form. (You can see any nonvisible lines by using the vertical scroll bar to scroll down.) Each time the loop is repeated, it adds 10 more lines to the text box object.

    TIP
    Worried about running out of room in the text box object? It will take a while if you're displaying only simple text lines. A multiline text box object has a practical limit of 32 KB of text! If you want even more space and formatting options, you can use the RichTextBox control in the Toolbox—a similar but even more capable control for displaying and manipulating text.

  14. Click the Close button on the form to stop the program.

As you can see, a For…Next loop can considerably simplify your code and reduce the total number of statements that you need to type. In the previous example, a loop three lines long processed the equivalent of 10 program statements each time you clicked the Loop button.

Creating Complex For…Next Loops

The counter variable in a For…Next loop can be a powerful tool in your programs. With a little imagination, you can use it to create several useful sequences of numbers in your loops. To create a loop with a counter pattern other than 1, 2, 3, 4, and so on, you can specify a different value for start in the loop and then use the Step keyword to increment the counter at different intervals. For example, the code

Dim i As Integer  Dim Wrap As String  Wrap = Chr(13) & Chr(10)    For i = 5 To 25 Step 5      TextBox1.Text = TextBox1.Text & "Line " & I & Wrap  Next i

displays the following sequence of line numbers in a text box:

Line 5  Line 10  Line 15  Line 20  Line 25

You can also specify decimal values in a loop if you declare i as a single-precision or double-precision type. For example, the For…Next loop

Dim i As Single  Dim Wrap As String  Wrap = Chr(13) & Chr(10)    For i = 1 To 2.5 Step 0.5      TextBox1.Text = TextBox1.Text & "Line " & i & Wrap  Next i

displays the following line numbers in a text box:

Line 1  Line 1.5  Line 2  Line 2.5

In addition to displaying the counter variable, you can use the counter to set properties, calculate values, or process files. The following exercise shows how you can use the counter to open Visual Basic icons that are stored on your hard disk in files that have numbers in their names. You'll find many icons, bitmaps, and animation files in the c:\program files\microsoft visual studio 8\common7\vs2005imagelibrary folder.

Open files by using a For…Next loop

  1. On the File menu, click the New Project command.

    The New Project dialog box appears.

  2. Create a new project named My For Loop Icons.

    Your new project starts, and a blank form appears in the Designer.

  3. Click the PictureBox control in the Toolbox, and then draw a medium-sized picture box object centered on the top half of the form.

  4. Click the Button control, and then draw a very wide button below the picture box. (You'll put a longer than usual label on the button.)

  5. Set the following properties for the two objects:

    Object

    Property

    Setting

    PictureBox1

    BorderStyle

    SizeMode

    Fixed3D

    StretchImage

    Button1

    Text

    “Display four faces”

  6. Double-click the Display Four Faces button on the form to display the event procedure for the button object.

    The Button1_Click event procedure appears in the Code Editor.

  7. Type the following For…Next loop:

    Dim i As Integer  For i = 1 To 4      PictureBox1.Image = System.Drawing.Image.FromFile _          ("c:\vb05sbs\chap07\face0" & i & ".ico")      MsgBox("Click here for next face.")  Next

    TIP
    The FromFile method in this event procedure is too long to fit on one line in this book, so I broke it into two lines by using a space and the line continuation character (_). You can use this character anywhere in your program code except within a string expression.

    The loop uses the FromFile method to load four icon files from the c:\vb05sbs\chap07 folder on your hard disk. The filename is created by using the counter variable and the concatenation operator you used earlier in this chapter. The code

    PictureBox1.Image = System.Drawing.Image.FromFile _    ("c:\vb05sbs\chap07\face0" & i & ".ico")

    combines a path, a file name, and the .ico extension to create four valid filenames of icons on your hard disk. In this example, you're loading face01.ico, face02.ico, face03.ico, and face04.ico into the picture box. This statement works because several files in the c:\vb05sbs\chap07 folder have the file name pattern facexx.ico. By recognizing the pattern, you can build a For…Next loop around the file names.

    NOTE
    The message box function (MsgBox) is used primarily to slow the action down so that you can see what's happening in the For…Next loop. In a normal application, you probably wouldn't use such a function (but you're welcome to).

  8. Click the Save All button on the Standard toolbar to save your changes. Specify the c:\vb05sbs\chap07 folder as the location.

  9. Click the Start Debugging button to run the program, and then click the Display Four Faces button.

    The For…Next loop loads the first face into the picture box, and then displays this message box:

    graphic

    NOTE
    If Visual Basic displays an error message, ensure that your program code has no typos, and then verify that the icon files are in the path you specified in the program. If you installed the Step by Step practice files in a folder other than the default folder, or if you moved your icon files after installation, the path in the event procedure might not be correct.

  10. Click OK to display the next face.

    Your screen looks something like this:

    graphic

  11. Click OK three more times to see the entire face collection.

    You can repeat the sequence if you want.

  12. When you're finished, click the Close button on the form.

    The program stops, and the development environment returns.

Opening Files by Using a Counter That Has Greater Scope

Are there times when using a For…Next loop isn't that efficient or elegant? Sure. In fact, the preceding example, although useful as a demonstration, was a little hampered by the intrusive behavior of the message box, which opened four times in the For…Next loop and distracted the user from the form, where we want his or her attention to be. Is there a way we can do away with that intrusive message box?

One solution is to remove both the MsgBox function and the For…Next loop, and substitute in their place a counter variable that has greater scope throughout the form. As you learned in Chapter 5, “Visual Basic Variables and Formulas, and the .NET Framework,” you can declare a variable that has scope (or maintains its value) throughout the entire form by placing a Dim statement for the variable at the top of the form in the Code Editor—a special location above the event procedures. In the following exercise, you'll use an Integer variable named Counter that maintains its value between calls to the Button1_Click event procedure, and you'll use that variable to open the same icon files without using the MsgBox function to pause the action.

Use a global counter

  1. Open the Code Editor for the My For Loop Icons project.

  2. Move the insertion point above the Button1_Click event procedure, and directly below the Public Class Form1 statement, declare an Integer variable named Counter by using this syntax:

    Dim Counter As Integer = 1

    Notice that Visual Studio separates the declaration that you've just entered from the event procedure with a solid line and displays the word “Declarations” in the Method Name list box. You've also done something unusual here—in addition to declaring the Counter variable, you've also assigned the variable a value of 1. This is a recent syntax option in Visual Studio (it arrived with Microsoft Visual Studio .NET 2002), and now and then you'll find it very handy to use. (Declaring and assigning at the same time isn't permitted in Visual Basic 6.)

  3. Within the Button1_Click event procedure, change the code so that it precisely matches the following group of program statements. (Delete any statements that aren't here.)

    PictureBox1.Image = System.Drawing.Image.FromFile _    ("c:\vb05sbs\chap07\face0" & Counter & ".ico")  Counter += 1  If Counter = 5 Then Counter = 1

    As you can see, I've deleted the declaration for the i integer, the For and Next statements, and the MsgBox function, and I've changed the way the FromFile method works. (I've replaced the i variable with the Counter variable.) I've also added two new statements that use the Counter variable. The first statement adds 1 to Counter (Counter += 1), and the second statement resets the Counter variable if the value has been incremented to 5. (Resetting the variable in this way allows the list of icon files to cycle indefinitely.) The Counter += 1 syntax is a shortcut feature in Visual Basic 2005—the functional equivalent of the statement

    Counter = Counter + 1

    Now you'll run the program.

    TIP
    The modified For Loop Icons program is available in the c:\vb05sbs\chap07\for loop icons folder.

  4. Click the Start Debugging button on the Standard toolbar to run the program.

    The program runs in the development environment.

  5. Click the Display Four Faces button several times. (Notice how the mood of the faces develops from glum to cheery.)

    graphic

  6. When you're finished, click the Close button on the form to stop the program.

As you can see, this solution is a little more elegant than the previous example because the user can click just one button, not a form button and a message box button. The shortcoming of the interface in the first program wasn't the fault of the For…Next loop, however, but rather the limitation I imposed that the Button1_Click event procedure use only local variables (in other words, variables that were declared within the event procedure itself). Between button clicks, these local variables lost their value, and the only way I could increment the counter was to build a loop. By using an Integer variable with a greater scope, I can preserve the value of the Counter variable between clicks and use that numeric information to display files within the Button1_Click event procedure.

The Exit For Statement

Most For…Next loops run to completion without incident, but now and then you'll find it useful to end the computation of a For…Next loop if a particular “exit condition” occurs. Visual Basic allows for this possibility by providing the Exit For statement, which you can use to terminate the execution of a For…Next loop early and move execution to the first statement after the loop.

For example, the following For…Next loop prompts the user for 10 names and displays them one by one in a text box unless the user enters the word “Done”:

Dim i As Integer  Dim InpName As String  For i = 1 To 10       InpName = InputBox("Enter your name or type Done to quit.")       If InpName = "Done" Then Exit For       TextBox1.Text = InpName  Next i

If the user does enter “Done”, the Exit For statement terminates the loop, and execution picks up with the statement after Next.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net