0% found this document useful (0 votes)
22 views34 pages

Week 7 - Loops

The document provides an overview of different types of loops in Visual Basic 2015, including: - For loops, which occur a certain number of times. - Do loops, which continue running until a certain condition is reached. - Specific loop types are described, such as For...Next loops, For Each...Next loops, Do Until loops, Do While loops, and nested loops. - Examples are given showing how to implement each loop type using sample code.

Uploaded by

10303374
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views34 pages

Week 7 - Loops

The document provides an overview of different types of loops in Visual Basic 2015, including: - For loops, which occur a certain number of times. - Do loops, which continue running until a certain condition is reached. - Specific loop types are described, such as For...Next loops, For Each...Next loops, Do Until loops, Do While loops, and nested loops. - Examples are given showing how to implement each loop type using sample code.

Uploaded by

10303374
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

LEARNING OBJECTIVES

• Students will learn the following:


• For…. Next Loops
• Using the Step Keyword
• Looping backwards
• For Each…..Next Loops
• Using Do Until…. Loops
• Using Do while… Loops
• Quitting Early
• Arrays
LOOPS
• When writing computer software, you often need to perform the same task
several times to get the effect you want.
• For example, you might need to create a telephone bill for all customers or read
in ten files from your computer’s disk.
• To accomplish this, you use a loop, and in this section you’ll take a look at the two
main types of loops available in Visual Basic 2015:
• For loops: These loops occur a certain number of times (for example, exactly ten
times).
• Do loops: These loops keep running until a certain condition is reached (for
example, until all the data is processed).
THE FOR…NEXT LOOP
• The simplest loop to understand is the For…Next loop.
• You will learn to build a For…Next Loop in this Try It Out
• Create a new Windows Forms Application project called Loops.
• Add a ListBox and a Button control to the form.
• Change the Name property of the ListBox to lstData and its IntegralHeight
property to False.
• Change the Name property of the button to btnForNextLoop.
• Set its Text property to For NextLoop.
• You’ll be adding more buttons later, so make this button a little wider, as shown in
Figure 4.17.
THE FOR…NEXT LOOP

• Double-click the button to create its Click event handler and add the following
bolded code:
THE FOR…NEXT LOOP
Private Sub btnForNextLoop_Click(sender As Object, e As EventArgs) Handles btnForNextLoop.Click
'Declare variable
Dim intCount As Integer
'Clear the list
ClearList()
'Perform a loop
For intCount = 1 To 5
'Add the item to the list
lstData.Items.Add("I'm item " & intCount.ToString & " in the list!")
Next
End Sub
• Now create the following method:
Private Sub ClearList()
'Clear the list
lstData.Items.Clear()
THE FOR…NEXT LOOP
• Save and run the project and then click the For Next Loop button.
• You should see results like those in Figure 4.18.

• NOTE When you’re talking about loops, you use the term iteration.
• One iteration includes one movement from the For statement to the Next
statement.
USING THE STEP KEYWORD
• You don’t have to start your loop at 1; you can pick any value you want.
• Nor do you have to increment the control value by 1 on each iteration; again, you
can increment by any value you want.
• In this Try It Out, you learn about the flexibility of the Step keyword.
• Return to the Forms Designer for the Loops project.
• Add a Button control to your form.
• Set its Name property to btnForNextLoopWithStep and its Text property to For
Next Loop w/ Step.
• Double-click the button and add the following bolded code in the Click event
handler:
USING THE STEP KEYWORD
Private Sub btnForNextLoopWithStep_Click(sender As Object, e As EventArgs) Handles btnForNextLoopWithStep.Click

'Clear the list


ClearList()
'Perform a loop
For intCount As Integer = 4 To 62 Step 7
'Add the item to the list lstData.Items.Add(intCount.ToString)
Next
End Sub

• Run the project and click the For Next Loop w/Step button.
• You will see results like those in Figure 4.19.
USING THE
STEP
KEYWORD
LOOPING BACKWARD
• By using a Step value that’s less than 0 (or a negative number), you can make the loop go
backward, rather than forward,
• In this example, you will make a loop go backward.
• Return to the Forms Designer and add another Button control to your form, setting its Name
property to btnBackwardsForNextLoop and its Text property to Backwards For Next Loop.
• Double-click the button and add the following bolded code in the Click event handler:
Private Sub btnBackwardsForNextLoop_Click(sender As Object, e As EventArgs) Handles btnBackwardsForNextLoop.Click

'Clear the list


ClearList()
'Perform a loop
For intCount As Integer = 10 To 1 Step -1
'Add the item to the list
lstData.Items.Add(intCount.ToString)
Next
LOOPING
BACKWARD

• Run the project and


click the Backwards
For Next Loop button.
You should see results
like those shown in
Figure 4.20.
THE FOR EACH…NEXT LOOP
• In practical, day-to-day work, it’s unlikely that you’ll use For…Next loops as
illustrated here.
• Because of the way the .NET Framework typically works, you’ll usually use a
derivative of the For…Next loop called the For Each…Next loop.
• In the algorithms you design, whenever a loop is necessary, you’ll have a
collection of things to work through, and sometimes this set is expressed as an
array.
• For example, you might want to look through all the files in a folder, looking for
those that are larger than a particular size.
• When you ask the .NET Framework for a list of files, you are returned an array of
strings, with each string in that array describing a single file.
• In this Try It Out, you’ll modify your Loops application so that it returns a list of
folders contained at the root of your C drive.
THE FOR EACH…NEXT LOOP
Private Sub btnForEachLoop_Click(sender As Object, e As EventArgs) Handles btnForEachLoop.Click

'Clear the list


ClearList()
'List each folder at the root of your C drive
For Each strFolder As String In My.Computer.FileSystem.GetDirectories("C:\")
'Add the item to the list lstData.Items.Add(strFolder)
Next
End Sub

• Run the project and click the For Each Loop button.
• You should see a list of folders that are at the root of your C drive.
THE DO…LOOP LOOPS
• The other kind of loop you can use is one that keeps happening until a certain
condition is met.
• This is known as a Do…Loop, and there are a number of variations.
• The first one you’ll learn about is the Do Until…Loop. This kind of loop keeps going
until something happens.
• Using the Do Until…Loop:For this Try It Out, you’re going to use the random
number generator that’s built into the .NET Framework.
• To create a loop that will keep generating random numbers until it produces the
number 10.
• When you get the number 10, you’ll stop the loop.
• Return to the Forms Designer in the Loops project, add another Button control to
your form, and set its Name property to btnDoUntilLoop and its Text property to Do
Until Loop.
• Double-click the button and add the following bolded code to its Click event
USING THE DO UNTIL…LOOP
Private Sub btnDoUntilLoop_Click(sender As Object, e As EventArgs) Handles btnDoUntilLoop.Click
'Declare variables
Dim objRandom As New Random
Dim intRandomNumber As Integer = 0
'Clear the list
ClearList()
'Process the loop until intRandomNumber = 10
Do Until intRandomNumber = 10
'Get a random number between 0 and 24
intRandomNumber = objRandom.Next(25)
'Add the number to the list
lstData.Items.Add(intRandomNumber.ToString)
Loop
USING THE DO
UNTIL…LOOP
• Run the project and click the
Do Until Loop button.
• You’ll see results similar to
the results shown in Figure
4.21.
• Keep clicking the button.
The number of elements in
the list is different each
time.
DO WHILE…LOOP
• The conceptual opposite of a Do Until…Loop is a Do While…Loop.
• This kind of loop keeps iterating while a particular condition is True. Let’s see it in
action.
• In this Try It Out, you will use a Do While…Loop to continue while a random
number is less than 15.
• Return to the Forms Designer and add another Button control to your form.
• Set its Name property to btnDoWhileLoop and its Text property to Do While
Loop.
• Double-click the button and add the following bolded code to the Click event
handler:
DO WHILE…LOOP
Private Sub btnDoWhileLoop_Click(sender As Object, e As EventArgs) Handles btnDoWhileLoop.Click
'Declare variables
Dim objRandom As New Random
Dim intRandomNumber As Integer = 0
'Clear the list
ClearList()
'Process the loop while intRandomNumber < 15
Do While intRandomNumber < 15
'Get a random number between 0 and 24
intRandomNumber = objRandom.Next(25)
'Add the number to the list
lstData.Items.Add(intRandomNumber.ToString)
Loop
DO WHILE…
LOOP
• Run the project and
click the Do While
Loop button.
• You’ll see something
similar to the results
shown in Figure
4.22.
OTHER VERSIONS OF THE DO…LOOP
• It’s possible to put the Until or While statements after Loop, rather than after Do.
Consider these two loops:

• NOTE When you use Loop While or Loop Until, you are saying that you want the
loop to execute at least once, no matter what.
• In general, it’s best to stick with Do While and Do Until, rather than use Loop While
and Loop Until.
Do While intX < 3 (Pre test)
intX += 1
Loop
• And
Do (Post test)
intX += 1
NESTED LOOPS
• You might need to start a loop even if you’re already working through another
loop.
• This is known as nesting, and it’s similar in theory to the nesting demonstrated
when you looked at If statements.
• In this Try It Out, you’ll see how you can create and run through a loop, even if
you’re already working through another one.
• In the Forms Designer, add another Button control to your form and set its Name
property to btnNestedLoops and its Text property to Nested Loops.
• Double-click the button and add the following bolded code to its Click event
handler:
NESTED LOOPS
Private Sub btnNestedLoops_Click(sender As Object, e As EventArgs) Handles btnNestedLoops.Click
'Clear the list
ClearList()
'Process an outer loop
For intOuterLoop As Integer = 1 To 2
'Process a nested (inner) loop
For intInnerLoop As Integer = 1 To 3
lstData.Items.Add(intOuterLoop.ToString & ", " & intInnerLoop.ToString)
Next
Next
End Sub
NESTED LOOPS

• Run the program and


click the Nested Loops
button.
• You should see results
that look like those
shown in Figure 4.23.
QUITTING EARLY
• Sometimes you don’t want to see a loop through to its natural conclusion.
• For example, you might be looking through a list for something specific, and when
you find it, there’s no need to go through the remainder of the list.
• In this Try It Out, you’ll look through folders on your local drive, but this time,
when you get to c:\Program Files, you’ll display a message and quit.
• Return to the Forms Designer, add another Button control to your form, and set
its Name property to btnQuittingAForLoop and its Text property to Quitting A For
Loop.
• Double-click the button and add the following bolded code to the Click event
handler:
QUITTING EARLY
Private Sub btnQuittingAForLoop_Click(sender As Object, e As EventArgs) Handles btnQuittingAForLoop.Click
'Clear the list
ClearList()
'List each folder at the root of your C drive
For Each strFolder As String In My.Computer.FileSystem.GetDirectories("C:\")
'Add the item to the list
lstData.Items.Add(strFolder)
'Do you have the folder C:\Program Files?
If String.Compare(strFolder, "c:\program files", True) = 0 Then
'Tell the user
MessageBox.Show("Found it, exiting the loop now.", "Loops")
'Quit the loop early
Exit For
End If
Next
QUITTING EARLY

• Run the program and


click the Quitting A For
Loop button.
• You’ll see something
similar to the results
shown in Figure 4.24.
QUITTING DO…LOOPS
• As you might have guessed, you can quit a Do…Loop in more or less the same
way, as you see in the next Try It Out.
• In this example, you will use Exit Do to quit a Do…Loop
• Return to the Forms Designer one last time and add another Button control to
your form.
• Set its Name property to btnQuittingADoLoop and its Text property to Quitting a
Do Loop.
• Double-click the button and add the following bolded code to the Click event
handler:
QUITTING DO…LOOPS
Private Sub btnQuittingADoLoop_Click(sender As Object, e As EventArgs) Handles btnQuittingADoLoop.Click
Declare variable
Dim intCount As Integer = 0
'Clear the list
ClearList()
'Process the loop
Do While intCount < 10
'Add the item to the list lstData.Items.Add(intCount.ToString)
'Increment the count by 1 intCount += 1
'Should you quit the loop
If intCount = 3 Then
Exit Do
End If
Loop
INFINITE LOOPS
• When building loops, you can create something called an infinite loop.
• This is a loop that, once started, never finishes. Consider this code:
Dim intX As Integer = 0
Do
intX += 1
Loop Until intX = 0
ARRAYS
• A fairly common requirement in writing software is the need to hold lists of
similar or related data.
• You can provide this functionality by using an array. Arrays are just lists of data
that have a single data type.
• For example, you might want to store a list of your friends’ ages in an integer
array or their names in a string array.
• This section explains how to define, populate, and use arrays in your applications.
• Defining and Using Arrays: An array is defined by entering the size of the array
after the variable name.
• For example, if you wanted to define a string array with 10 elements, you’d do
this:
• Dim strName(9) As String
DEFINING AND USING A SIMPLE ARRAY
• In Visual Studio 2015, click File ➪ New Project. In the New Project dialog, create a
new Windows Forms Application called Array Demo.
• When the Designer for Form1 appears, add a ListBox control to the form. Using
the Properties window set its Name property to lstFriends and its IntegralHeight
property to False.
• Add a Button control to the form. Set its Name property to btnArrayElement and
set its Text property to Array Element. Arrange your controls so that your form
looks similar to Figure 5.1 because you’ll be adding more Button controls to this
project later.
ARRAYS
• Double-click the button and add the following bolded code to its Click event handler.
Private Sub btnArrayElement_Click(sender As Object, e As EventArgs) Handles btnArrayElement.Click
'Clear the list ClearList()
'Declare an array
Dim strFriends(4) As String
'Populate the array
strFriends(0) = "Wendy"
strFriends(1) = "Harriet"
strFriends(2) = "Jay"
strFriends(3) = "Michelle"
strFriends(4) = "Richard"
For Each strName As String In strFriends
'Add the array item to the list
lstFriends.Items.Add(strName)
Next
SUMMARY
TOPIC CONCEPT
For….Next Loop This is the simplest of the two for loops in visual basic. Executes a piece of code a number of
Using the Step Keyword times. Slide 4 and 5 shows how to use the for… Next loop
Looping backwards The Step keyword is used to increase the start value during each iteration. If it is not specified, a
default value of 1 is used. Slide 7 shows how to use the step keyword.
To look backward the lower limit value should be the highest and the upper limit value should be
the lowest. Then the step value should be negated. Slide 9 demonstrates how this is done.
For Each…. Next Loop The design of the .Net framework makes it more convenient to use this type of For Loop. Slide 12
demonstrates this.
Do Until…Loops This kind of loop keeps executing until a condition is true. Slide 16 and 15 shows how this is done.
Do While…Loops This is the exact opposite of DO Until…Loop. This kind of loop will continue to execute as long as a
Nested Loops condition is true. Slide 17 and 18 shows how to do this.
Sometimes there is a need to start a loop in an existing loop. This is referred to as loop within a
loop or nested loops. Slide 21 and 22 demonstrates this.
Quitting Early Sometimes there is a need to exit the loop even though the loops condition is not met. To do this
use the keep word Exit For or Exit Do. Slides 24, 25 and 27 illustrates this
Arrays This is a data structure for holding a list of similar or related data. Arrays like all other variables
must be defined before usage. Slide 31 shows how to use arrays in visual basic.
Assignment III
• Write a program in Visual Basic that does following:
• Asks the user to enter the total number of Names to sort
• Asks the user to specify the sort order (Ascending or Descending)
• Uses a loop to accept the names to sort
• Sorts the names based on the sort order provided by the user

You might also like