1 Lesson 4 — Decisions, Looping, Arrays, and Searching

advertisement
Lesson 4 — Decisions, Looping,
Arrays, and Searching
Microsoft Visual Basic
.NET, Introduction to
Programming
1
Objectives







2
Plan the solution to a programming problem.
Understand and apply the rules of logic to complex
True/False expressions.
Write advanced lf-Then-Else End If statements.
Write Do-While and Do-Until statements.
Create program loops that depend on logical
expressions.
Declare and use arrays.
Use built-in functions for a variety of tasks.
Vocabulary









3
Algorithm
Array
Binary search
Concatenation
Counting statement
Data structure
Debugging line
Declarations
Element








Error trapping
statements
Flag
Index
Items collection
Lifetime
Linear search
Member
Mod
Vocabulary




4
Private variable
Running total
Sentinel
Stepwise refinement




Subroutine
Subscript
User interface
Visibility
Approaching a Problem






5
Collect information.
Create the user interface.
Develop the algorithm.
Subdivide the problem.
Choose data structures.
Write the code.
Collect Information
Start by getting all the information you can
about the problem. Talk to the users who will
run the program. Find out what they want.
Do not assume that you know more about
their problems than they do. Gather as much
information as you can, but expect to revise
your solution later to meet unexpected or
newly discovered needs.
6
Create the User Interface
The user interface is how the user will
interact with the program. It is what the user
keys and clicks. It is what the user sees as
output. You can create a Visual Basic
program that is "all show." Design the forms
used to enter data. Design the forms that
display the information. Once these samples
are created, return to the user. Find out if
your mock solution is what the user expects.
7
Develop the Algorithm
Solve the problem completely on paper. If
you cannot solve a problem with paper, a
pencil, and a calculator, you probably will not
be able to program the computer to solve the
problem. The step-by-step solution to a
problem is called an algorithm. The word
algebra comes from the same root.
8
Subdivide the Problem
Subdivide each section into smaller and
smaller tasks. Once you’ve divided the
problem, each part can be approached
individually. Usually these smaller problems
are easy to solve. Even if they are not, you
have at least modularized the problem, and
you can tackle the tough parts later in the
process. This process is called stepwise
refinement.
9
Event Procedure
An event procedure is a subroutine
connected with an action performed on an
object like the Click event of a text box or
button. When a button or menu item is
clicked, the code associated with that event
is executed. The Click event is one of many
events that an object may respond to.
10
Choose Data Structures



11
A data structure is a way to organize data. The
simplest way to represent data is to use variables.
Another important data structure is the array. An
array is a list of values referred to by a single
variable name. Values in an array may be numbers
or strings, or they may represent complex data types
that include many pieces of information.
Other data structures organize data according to
relationships between the individual data items.
Write the Code
Writing the code may be the very last thing
you do. Or it may not be. Be flexible. It may
be wise to develop an algorithm and write the
code to solve a particular piece of the
problem before the user interface is designed
or before a data structure is chosen. You
may need to experiment with different
solutions or different data structures to find
the one that fits best.
12
Important!!
Don't be afraid to start over. The things you
learn in your first attempt will make your
second attempt better.
13
ListBox and ComboBox
The ListBox control is a display tool that lets you
display lists of values. It also allows the user to
select items from the list for further processing.
The ComboBox control is closely related to the
ListBox control. When you select an item from the
Class Name box in the Code window, you are using
a combo box. A combo box is like a text box, but it
supplies the user with a list of suggested entries.
14
Items Collection
The entries displayed in a list box or combo
box are called items. All the items together
form the Items collection. A collection is
itself an object that contains other related
objects. In this case, the objects of the
collections are the entries in the list box or
combo box.
15
Note
In many fonts, a lowercase L is nearly
indistinguishable from the numeral 1 or an
uppercase I (eye). The context should tell
you which to use. The three-letter prefix for
the name of a list box is lst, except each
character is lowercase.
16
‘ Initialize the ComboBoxes
cboCapacity.Items.Add("30 gallon")
cboCapacity.Items.Add("40 gallon")
cboCapacity.Items.Add("50 gallon")
cboPower.Items.Add("Natural Gas")
cboPower.Items.Add("Electric")
cboPower.Items.Add("LP Gas")
cboWarranty.Items.Add("1 year")
cboWarranty.Items.Add("5 years")
cboWarranty.Items.Add("8 years")
cboWarranty.Items.Add("10 years")
17
Note
The single quote ‘ character starts a
comment. Comments are normally displayed
in a green font.
18
Final Appearance of frmWaterHeater
19
Note
To enter repetitive code, select the part of the
code that repeats. Select Edit|Copy from the
menu bar, or press Ctrl+C to copy the
selected code. Move the cursor to the
beginning of the next line and paste the code
by selecting Edit|Paste or by pressing Ctrl+V.
Once the code is copied a sufficient number
of times, go back and edit each line.
20
lstQualifying.Items.Clear()
lstQualifying.Items.Add(cboCapacity.Selecteditem)
lstQualifying.Items.Add(cboPower.SelectedItem)
lstQualifying.Items.Add(cboWarranty.Text)
21
Program Decisions
The simplest version of the If statement takes
only a single line:
If condition Then statement
NOTE:
The one-line If statement is the original
version. Many early versions of BASIC were
limited to this kind of If.
22
Boolean or Logical Expression
An expression that, when evaluated, results
in a True or False answer.
If the condition tested is True, the statement
or statements following Then are executed. If
the condition tested is False, the
statement(s) after Then are skipped. In either
case, the statements following the If
statement are executed.
23
Other Versions of the If Statement
If condition Then
Statement (s)
End If
24
Other Versions of the If Statement
If condition Then
Statement(s) of the True branch
Else
Statement(s) of the False branch
End If
25
Nesting If Statements
If Age < 2 Then
Person = "Infant"
Else
If Age <= 5 Then
Person = "Toddler"
Else
Person = "Older Child"
End If
End If
26
ElseIf
If Age < 2 Then
Person = "Infant"
ElseIf Age <= 5 Then
Person = "Toddler"
Else
Person = "Older Child"
End If
27
Three Ifs
If Age < 2 Then Person = "Infant"
If 2 <= Age And Age <= 5 Then Person =
"Toddler"
If Age > 5 Then Person = "Older Child"
28
Select Case Statement
Select Case textexpression
Case expressionlist
Case expressionlist
Statement(s)
Statement(s)
Case Else
Statement(s)
End Select
29
Simple Example
Select Case Choice
Case 1
txtShowOne.Visible = True
Case 2
MessageBox.Show "Show Two"
Case Else
MessageBox.Show "Not one or two."
End Select
30
Ranges
Select Case Age
Case Is < 2
Person = "Infant"
Case 2 To 5
Person = "Toddler"
Case 6 To 12
Person = "Preteen"
Case 13 To 19
Person = "Teenager"
Case 20,21,22
Person = "Young adult"
Case Is > 22
Person = "Older adult"
End Select
31
Adding Items to the Items Collection
32
Dim Index As Integer = lstCardList.SelectedIndex
Messagebox.Show("Selected index:" & Index.ToString, "Index")
Select Case Index
Case 0 'Discover card
Messagebox.Show("$1500", "Credit Limit:")
Case 1 'MasterCard
Messagebox.show("$2000", "Credit Limit:")
Case 2 'VISA
Messagebox.Show("$3000", "Credit Limit:")
Case 3 'VISA Gold
Messagebox.Show("$3500", "Credit Limit:")
Case 4 'Platinum
Messagebox.Show("$5000", "Credit Limit:")
Case Else
Messagebox.Show("Illegal Entry")
End Select
Debugging Line
A debugging line is a line of code included in the
program to let the user know what is going on as the
code is executed. In the final version of the
application, there is no need to display the value of
Index. Open the Code window, locate the
Messagebox.Show statement that displays the value
of Index, and put a single quote at the beginning of
the line. This is called commenting out a line of code
because the single quote character turns the whole
line into a comment. Commenting out a debugging
line is better than deleting it because, when the
program is modified, the line may once again be
needed.
34
Programming Skills
Characters or strings can also be used to select different
cases, as shown below:
Select Case FirstName
Case "Groucho"
Statements(s)
Case "Harpo"
Statements(s)
Case "Chicko"
Statement(s)
Case Else
Statements(s)
End Select
35
A Lesson in Repetition
For loops are called definite loops because the
starting point, the upper limit, and the increment are
all known before the loop begins. But it is not always
possible to know the number of repetitions
necessary for a loop before the loop begins. You
may need to process records from a database until
you run out of data. Or you may need to process
data from the keyboard until a special ending value,
called a sentinel value, is entered. For these
situations, use an indefinite loop.
36
Do While
Do While condition
Body
Loop
37
Do While Example
In the loop below, the value of x is initialized to 1 before the
loop starts. The condition x < 100 is evaluated before the body
of the loop is executed. Since the condition is True, the
statement in the body of the loop is executed. The value of x is
reassigned to 2 * 1 + 1, or 3. The Loop statement at the end
sends the program flow back to the top of the loop. At the top of
the loop, the condition is tested again to see if it is True. Since it
is still True, the loop repeats.
x=1
Do While x < 100
x=2*x+1
Loop
38
Do-While Testing at the End
Do
Body
Loop While condition
39
An Example
Dim PopBottles As Integer
Do
PopBottles = CInt(InputBox("Enter the
number of broken bottles:"))
Loop While PopBottles > 0
40
Do-Until
41
Do Until condition
Body
Loop
Example:
X=1
Do Until x > 100
x=2*x+1
Loop
Do-Until
X=1
Do
Body
Loop Until x > 100
42
Divisibility
To test divisibility, you use the Mod operator. The
Mod operator divides one whole number by another
and returns the remainder of the division. Five mod
three is two since three goes into five one time with a
remainder of two. If two numbers are divided and the
remainder is 0, the first number is divisible by the
second. Fifteen Mod five is 0 because five goes into
fifteen evenly, leaving a remainder of 0.
To test to see if a number is even, divide it by two. If
the number is divisible by two, then number Mod two
will equal 0. If the number is odd, the remainder is
one.
43
The Goldbach Conjecture
Take any positive whole number. If the number is
even, divide it by two. If the number is odd, multiply it
by three and add one. Goldbach claimed that the
series of numbers generated by applying these two
rules always ends with a one.
For example, if you start with the number 7, since it
is odd, multiply by 3 and add 1. The result is 22.
Since 22 is even, divide by 2. The result is 11. The
sequence generated is 7, 22, 11, 34, 17, 52, 26, 13,
40, 20, 10, 5, 16, 8, 4, 2, and 1.
44
lstDisplay.Items.Clear()
45
Dim x As Integer
Do
x = CInt(InputBox("Enter a positive whole number:", "Goldbach", "7"))
Loop Until x > 0
lstDisplay.Items.Add(x.ToString)
Do While x <> 1
If x Mod 2 = 0 Then
x=x/2
Else
x=3*x+1
End If
lstDisplay.Items.Add(x.ToString)
46
Loop
Dim x As Integer, y As Integer, Largest As Integer
x=1
Do
x=x+1
Largest = x
y=x
lstDisplay.Items.Clear()
lstDisplay.Items.Add(y)
47
Do While y <> 1
If y Mod 2 = 0 Then
y=y\2
Else
y=3*y+1
End If
lstDisplay.Items.Add(y)
If y > Largest Then
Largest = y
End If
Loop
Loop Until Largest > 1000
48
Programming Skills
The section of the code shown below:
If y > Largest Then
Largest = y
End If
49
These lines compare the current value of y with a
value stored in Largest. If the value of y exceeds the
value of Largest, the value of y is saved in Largest.
This allows the programmer to find the largest (or
smallest) item in a list and save that value for later
processing.
The Counting Statement, x = x + 1.
Algebraically, this is not a valid equation, but
it works fine in a program. It is not an
equation at all, but it is an assignment
statement. Evaluation starts on the right side
of the equal sign. The value of x is found,
one is added, and the result is assigned back
to the variable x. This is a common statement
that may occur several times in the same
program.
50
Running Total: Total = Total + x
Evaluation starts on the right side of the equal sign.
The value of Total is fetched from memory. The value
of x is added to the Total and the result is assigned
back to the variable, Total. What normally happens in
a checkbook is that a total is written at the top of the
page, then check amounts are entered on each line
and subtracted from the running total. Running totals
are common in programs.
51
Arrays
An array is a list of values referred to by a single
name. Arrays make it easy to access a list of related
values. Arrays store lists of names, values, or
objects. An array is an appropriate data structure
anytime you want to hold a list of values in memory
for further processing or display.
You declare an array in a Dim statement by following
a variable name with a number enclosed in
parentheses.
Dim ClassList(45) As String
Dim Scores(10) As Integer
52
Putting Values into an Array
Dim ClassList(10) As String
Dim Index As Integer
For Index = 0 To 9 'Valid indices from 0 to 9.
ClassList(Index) = InputBox("Enter name[" &
Index.toString & "]:")
Next
53
The Out-of-Range Error Message
54
Linear Search
Dim Target As String
Target = InputBox("Enter the target:")
For Index = 0 To 9
If Target = ClassList(Index) Then
Exit For
End If
Next
MessageBox.Show(Index.ToString)
55
Scope of a Variable
The scope of a variable is its visibility and its
lifetime. The lifetime of a variable is when it does
and does not hold valid values. Most variables have
a limited life. They come into existence at the
beginning of an event procedure and disappear
when the procedure ends. They reappear when the
procedure is again executed.
56
The visibility of a variable is the point at which the
value of the variable is available to use or change. A
variable declared with a Dim statement in one event
procedure is normally not available (visible) in
another event procedure. Such a variable is a
private variable.
Final Placement of Controls on
the Form
57
Dim FirstName(5) As String
Dim Current As Integer
Current is used to keep track of the next empty
space in the array. Visual Basic automatically
initializes its value to 0. It is also used when names
are added to the array. When the value of Current
exceeds the last valid array subscript, the program
refuses to accept further input. Current is declared in
Declarations along with the array because its lifetime
must equal the lifetime of the form.
58
If Current < 5 Then
FirstName(Current) = InputBox("Enter a first name:")
lstDisplay.Items.AddFirstName(Current)
Current = Current + 1
Else
MessageBox.Show("Array capacity exceeded!")
End If
59
lstDisplay.Items.Clear
Dim Index As Integer
For Index = 0 To 4
FirstName(Index) = " "
Next
Current = 0
btnEnter.Focus
60
Dim Target As String, Index As Integer
Dim Found As Boolean
Do
Target = InputBox("Enter the name for which to search:")
Loop Until Target <> ""
Found = False
'Initialize the Boolean variable.
For Index = 0 To Current - 1
If Target = FirstName(Index) Then
Found = True
Exit For
End If
Next
61
If Found Then
MessageBox.Show(Target.ToString & " found at " &
Index.ToString)
Else
MessageBox.Show(Target.ToString & ": not in list.")
End If
62
Binary Search
The binary search is a powerful algorithm to find a target in an
ordered list. If you use a linear search to find a target in an
unordered list of 100, you will have, on average, 50
comparisons before you find the target. Each time the If
statement compares the target to an item in the list, it is a
comparison. The number of comparisons is proportional to the
number of items in the list. If there are n items in the list, it takes
an average of n/2 comparisons to find the target in an
unordered list.
The binary search can find an item in an ordered list of 100 with
no more than seven comparisons. It can search a list of 1000
items with no more than 10 comparisons. The linear search
would average 500 comparisons with a list of 1000.
63
Binary Search
The reason the binary search is so efficient is that,
with every comparison, the list is cut in half. The
search starts by comparing the target with the middle
of the list. If the target is equal to the item examined,
the search is over. If the target is alphabetically less
than the middle, the bottom half of the list is thrown
out. The list is redefined to include just the items in
the top half of the list and the process is repeated.
With every comparison, the list of the remaining
items is cut in half. Every time the size of the list
doubles, only one additional comparison is needed
to complete the search.
64
Binary Search, Setup
Dim Target As String
Dim High, Low, Md, Position As Integer
'Assume lstDisplay is filled with names and Sorted = True
Position = 0
Low = 0
High = lstDisplay.Items.Count - 1
65
Binary Search, Loop
Do While Low <= High
Md = (Low + High) \ 2
If Target = lstDisplay.Items(Md) Then
Position = Md
Exit Do
ElseIf Target < lstDisplay.Items(Md).ToString Then
High = Md - 1
Else
Low = Md + 1
End If
Loop
66
Binary Search, Finish
If Low <= High Then
MessageBox.Show("Found " & Target & “
at position:" & Position)
else
MessageBox.Show("The Target has not
been found.")
End If
67
Festival of Strings
68
Summary







69
The planning and execution of a programming application can be
broken down into the following steps:
Collect information from the user about the intended use of the
application.
Create the user interface and show the result to the user. Alter the
design in accordance with the user's needs.
Develop the algorithm used to solve the problem. Work the
problem out with paper, pencil, and a calculator before trying to
solve it on the computer.
Subdivide the problem by breaking it into smaller and smaller
pieces. Plan the interaction of all pieces.
Choose data structures to represent the data processed in the
program. This choice may be determined by the algorithm and
must be carefully made to optimize both run time and storage
space.
Write the code needed to solve each small problem. If the
planning is careful and complete, the code will fit together like a
puzzle.
Summary





70
A combo box lets the user choose an item from a list.
It is most like the text box control.
There are several versions of the If statement.
Logical expressions used to build the conditions
tested in If statements can be combined using And,
Or, and Not.
The Select Case statement replaces a series of IfThen statements.
The Do-While and Do-Until statements build
indefinite loops. These loops are controlled by
conditions within the loop itself.
Summary



71
Arrays are lists of values referred to by the same name. The
elements or members of the array are uniquely selected by
specifying an index or subscript value.
A linear search is used to search for a target value in an array.
It works by sequentially searching every item in the list. The
average number of comparisons made by the linear search
while searching for a target among n elements of the list is
about n/2.
A binary search can search an ordered list with a handful of
comparisons. The maximum number of comparisons is the
value of x in the equation 2x = n, where n is the number of
items in the list.
Summary


72
If the Sorted property of a list box is set to
True, the elements of the list box are always
displayed in alphabetical order.
Visual Basic uses a large number of
functions to handle special jobs involving
mathematics and string manipulation.
Download