Hot-Link Menu in Right-Side Column
Last Updated 6-30-2010
7.1 Why use Loops?
Repetition structures, known as loops, offer a flexible yet convenient way to repeatedly process instructions in a program. Loops have many applications in computer programming. For example, when one searches for a certain product on eBay or when searching Google, the program uses a loop to search through many records and finds those with matching or similar keywords. Loops are also used in computer graphics programming, such as animation. Many frames are displayed within a loop showing an animation. Loops are also used when programming microprocessors and computing numerical series.
There are three basic programming structures that are used in high-level programming languages. These structures are sequential, selection, and repetition. The sequential structure is a segment of code where the statements get executed in a sequence from top to bottom. The selection structure involves an If or a Select/Case statement, where the program execution branches to a new line, based on the outcome of a decision. The repetition structure, often referred to as a Loop, is used when a segment of code needs to be executed repeatedly. Usually, a condition controls the continuation of a loop. There are different repetition structures available in Visual Basic VB.NET.
There are certain terms that are used when working with loops. Here are some of the common terms that you should familiarize yourself with before reading any further:
7.4 Different Kinds of Loops
In general, there are two categories of loops: pretest loops and posttest loops.
In a pretest loop, the condition gets evaluated at the beginning of the loop cycle. Therefore, the body of the loop will not get executed if the condition does not hold the very first time.
In a posttest loop, the loop condition gets evaluated at the end of the loop cycle. Therefore, the body of the loop will get executed at least once, regardless of the condition. This is a major difference between a pretest loop and a posttest loop. You may choose a posttest loop if the problem description justifies the body of the loop be executed at least once.
Repetition Structures in Visual Basic VB.NET
The first three loop structures are important. Any problem that requires repetition can be coded using one of these loops. The other loop structures are provided for your information and are not used as often.
Actually, there is one more repetition structure: For Each...Next, which can be used when processing array elements. This loop structure will not be discussed in this chapter. If you would like to learn more about the For Each...Next, refer to online resources.
The For loop is also known as a counting loop. It is an ideal loop structure when the number of iterations is known. It always contains a loop variable that works like a counter. The For loop is a powerful loop structure, in the sense that the initialization of the loop variable, to loop condition, and the updating of the loop variable are all embedded in the syntax of the loop. Below is the general syntax of the For loop.
General Syntax (keywords are in bold):
When a For loop begins, the LoopVariable gets initialized to the InitialValue. This initialization happens only once. The range of the values that the LoopVariable can assume is from the InitialValue to the EndValue.
Key Points to Remember
Assignment: Write a For loop to display "Hail Purdue" ten times in a label.
This is an ideal problem to solve using a For loop, because it is a counting problem and the number of iterations is known. A computer program to solve this problem needs one variable that is used as a counter. The loop should iterate ten times, and each time "Hail Purdue" should be displayed in the label. The most natural way of counting ten times is from 1 to 10. Therefore, the loop variable may start with the initial value of 1 and go up to the end value of 10, with the step value of 1. Below is the pseudocode for this solution:
Create a Label changing the characteristics as indicated in the diagram below:
Solution to 7.1
Visual Basic VB.NET - EXAMPLE 2
Assignment: Write a For loop to add up all the numbers from 1 to 100, i.e. 1+2+3...+100.
This is also a good problem to solve using a For loop, because the number of iterations is known. To write a computer program for this problem, you need two variables: one variable to add up the numbers and a loop variable to assume the values 1, 2, ...100. Hence, the loop variable should start with the initial value of 1, and go up to the end value of 100, with the StepValue of 1. In the body of the loop, the loop variable should be added to the sum of the numbers. Let us look at the pseudocode followed by the program to solve this problem.
Create a Label for output changing the characteristics as indicated in the diagram below. Change the Form Text to Sum 1 to 100 and double-click on the form to enter the text in the diagram below:
Solution to 7.2
For Loop with Negative Step Value
Sometimes the logic of the problem requires a For loop with negative step values. In such cases, the initial value must be greater than the end value for the loop to execute. In other words, the loop variable starts with the initial value and steps down to the end value.
For example, the following loop displays the numbers from 10 to 1 in a Label:
The Do-While is a pretest loop. It is a good choice when the number of iterations is not known and the logic of the problem suggests that the loop should continue as long as a condition evaluates to TRUE. To understand the logic of the Do-While loop, let us consider something realistic. For example, the night before the exam, a student thinks "I will keep studying, while the library is open" or a person in a casino says "I will keep putting quarters in the slot machine, while I have quarters in my pocket." There is usually a loop variable that is used to from the condition of the loop. Unlike the For loop, the initialization and updating ofthe loop variable is not a part of the syntax. Below is the general syntax of the Do-While loop:
Visual Basic VB.NET - EXAMPLE 3
Assignment: Write a Do-While loop to add up all the numbers from 0 to 100, i.e. 0+1+2+3...+100.
Although this is an ideal problem to code using a For loop, you may, use a Do-While loop as well. As explained before, to write a computer program for this problem, you need two variables: one variable to add up the numbers and a loop variable to assume the values 0,1,2...100. The variables should be initialized to 0 before the loop. Although VB.Net initializes all the numeric values to 0, it is a good practice to explicitly initialize the variables and their initial values. the condition of the loop should be formed for the continuation of the loop. Therefor the condition should be while the loop variable is less than or equal to 100. In the body of the loop, the loop variable should be added to the sum of the numbers, and then incremented by 1 to assume the next value. Below is the pseudocode for this problem using a Do-While loop.
Create a Label for output changing the characteristics as indicated in the diagram below. Change the Form Text to Do-While Sum 0 to 100 and double-click on the form to enter the text in the diagram below:
Solution to 7.3
Visual BasicIntroduction to VB.NET
How VB is Compiled
Start Visual Studio
Windows Form App
Save Your WorkVB OOP Programming
Visual Basic Code
Button Event CodeCoding Recommendations
Error List Window
Built-In Data Types
Declare VariablesDeclare Constants
Code Arithmetic Expressions
Math ClassString Declaration
Loop ConstructsFor Next Loop
Do While Loop
Do Until LoopDo...Loop-While
Exit Do | Exit ForDo...Loop
Rnd( ) FunctionListbox Control
Parallel ArraysKey Event Args
Dynamic ArraysRedimension Array
MultiDimensional ArraysDataGridView Control
Length and Sort Methods
Add Form To Project
Form Object Methods
Form Show Method
Form Close Method
Form Accept Button
Multiform Project Example
ASP.NET Web ProgrammingCreate Data Source
Configure Access Data Source
Add Product Class
Extract Local Database DataOrder PageLoad VB Code
Add New Web Page
Set Start PageDisplay Cart Aspx Code
Display Cart Design View
Sorted List Definition
VB.NET Session State
Create CartItem ClassGetCartContents Function
Add To Cart Event HandlerRemove Cart Item Event
Clear Cart Event Handler