Chapter 5 – Control Structures: Part 2 Outline

advertisement
1
Chapter 5 – Control Structures: Part 2
Outline
5.1
Introduction
5.2
Essentials of Counter-Controlled Repetition
5.3
For/Next Repetition Structure
5.4
Examples Using the For/Next Structure
5.5
Select Case Multiple-Selection Structure
5.6
Do/Loop While Repetition Structure
5.7
Do/Loop Until Repetition Structure
5.8
Using the Exit Keyword in a Repetition
Structure
5.9
Logical Operators
 2002 Prentice Hall. All rights reserved.
2
5.2 Essentials of Counter-Controlled
Repetition
• Elements needed
– Control variable
• Used to determine whether loop continues to iterate
– Initial value of control variable
– Increment (or decrement)
• Describes how control variable is modified during each
iteration
– Condition
• Tests for final value of control variable
 2002 Prentice Hall. All rights reserved.
3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
' Fig. 5.1: WhileCounter.vb
' Using the While structure to demonstrate counter-controlled
' repetition.
Control variable defined
Module modWhileCounter
Whileand
structure
initialized to 2
used for repetition
Sub Main()
Condition tests if control
variable is less than or equal to
Dim counter As Integer = 2 ' initialization
final value
Outline
WhileCounter.vb
While (counter <= 10) ' repetition condition
Console.Write(counter & " ")
counter += 2 ' increment counter
End While
End Sub ' Main
Control variable incremented
by 2 each iteration
End Module ' modWhileCounter
2 4 6 8 10
 2002 Prentice Hall.
All rights reserved.
4
5.3 For/Next Repetition Structure
• For/Next counter-controlled repetition
– Structure header initializes control variable, specifies final
value and increment
• For keyword begins structure
– Followed by control variable initialization
• To keyword specifies final value
• Step keyword specifies increment
– Optional
– Increment defaults to 1 if omitted
– May be positive or negative
– Next keyword marks end of structure
– Executes until control variable greater (or less) than final
value
 2002 Prentice Hall. All rights reserved.
5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
' Fig. 5.2: ForCounter.vb
' Using the For/Next structure to demonstrate counter-controlled
' repetition.
Module modForCounter
Control variable
To specifies
initialized toStep
2
increments counter
final value of 10
by 2 each iteration
Outline
ForCounter.vb
Sub Main()
Dim counter As Integer
' initialization, repetition condition and
' incrementing are included in For structure
For counter = 2 To 10 Step 2
Console.Write(counter & " ")
Next
End Sub ' Main
Next marks
end of loop
End Module ' modForCounter
2 4 6 8 10
Program Output
 2002 Prentice Hall.
All rights reserved.
6
5.3 For/Next Repetition Structure
For
keyword
Initial value of
control variable
Final value of
control
variable
Increment of control
variable
For counter = 2 To 10 Step 2
Control variable
name
Fig. 5.3
 2002 Prentice Hall. All rights reserved.
To
keyword
Step
keyword
Components of a typical For/Next header.
7
5.4 Examples Using the For/Next Structure
• Examples
– Vary the control variable from 1 to 100 in increments of 1
• For i = 1 To 100
• For i = 1 To 100 Step 1
– Vary the control variable from 100 to 1 in increments of –1
• For i = 100 To 1 Step –1
– Vary the control variable from 7 to 77 in increments of 7
• For i = 7 To 77 Step 7
– Vary the control variable from 20 to 2 in increments of –2
• For i = 20 To 2 Step -2
 2002 Prentice Hall. All rights reserved.
8
5.4 Examples Using the For/Next Structure
Establish initial value
of control variable
counter = 1
Determine if final
value of control
variable has been
reached
counter < = 10
(implicit)
false
Fig. 5.4
true
Console.WriteLine(
counter * 10)
Body of loop
(this can be multiple
statements)
counter += 1
(implicit)
Increment the control
variable
Flowcharting a typical For/Next repetition structure.
 2002 Prentice Hall. All rights reserved.
9
1
' Fig. 5.5: Sum.vb
2
' Using For/Next structure to demonstrate summation.
3
4
Imports System.Windows.Forms
Control variable
5
counts by 2, from
6
Module modSum
2 to 100
7
Value of number is added in
8
Sub Main()
each iteration to determine sum
9
10
Dim sum = 0, number As Integer of even numbers
Text displayed
11
12
' add even numbers from
2 to 100
in dialog
Display
a
MessageBox
13
For number = 2 To 100 Step 2
Text displayed in
14
sum += number
title bar
15
Next
16
17
MessageBox.Show("The sum is " & sum, _
18
"Sum even integers from 2 to 100", _
19
MessageBoxButtons.OK, MessageBoxIcon.Information)
20
End Sub ' Main
21
Indicate
22
End button
Moduleto'be
modSum
OK button
Outline
Sum.vb
Program Output
Indicate icon to be
Information icon
 2002 Prentice Hall.
All rights reserved.
10
5.4 Examples Using the For/Next Structure
MessageBoxIcon C o nsta nts
Ic o n
De sc rip tio n
MessageBoxIcon.Exclamation
Icon containing an exclamation point.
Typically used to caution the user
against potential problems.
MessageBoxIcon.Information
Icon containing the letter "i." Typically
used to display information about the
state of the application.
MessageBoxIcon.Question
Icon containing a question mark.
Typically used to ask the user a
question.
Icon containing an in a red circle.
Typically used to alert the user of
errors or critical situations.
MessageBoxIcon.Error
Fig. 5.6
 2002 Prentice Hall. All rights reserved.
Icons for message dialogs.
11
5.4 Examples Using the For/Next Structure
Me ssa g eBoxButton c o nsta nts
De sc rip tio n
MessageBoxButton.OK
OK button. Allows the user to acknowledge a
message. Included by default.
MessageBoxButton.OKCancel
OK and Cancel buttons. Allow the user to
either continue or cancel an operation.
MessageBoxButton.YesNo
Yes and No buttons. Allow the user to respond
to a question
MessageBoxButton.YesNoCancel
Yes, No and Cancel buttons. Allow the user to
respond to a question or cancel an operation.
MessageBoxButton.RetryCancel
Retry and Cancel buttons. Typically used to
allow the user to either retry or cancel an
operation that has failed.
MessageBoxButton.AbortRetry-
Abort, Retry and Ignore buttons. When one
of a series of operations has failed, these butons
allow the user to abort the entire sequence, retry
the failed operation or ignore the failed
operation and continue..
Ignore
Fig. 5.7
Button c o nsta nts for m essa g e d ia log s.
Fig. 5.7
 2002 Prentice Hall. All rights reserved.
Button constants for message dialogs.
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
' Fig. 5.8: Interest.vb
' Calculating compound interest.
Imports System.Windows.Forms
Module modInterest
Outline
Type Decimal used for
precise monetary
calculations
Interest.vb
Sub Main()
Dim
Dim
Dim
Dim
amount, principal As Decimal ' dollar amounts
rate As Double
' interest rate
year As Integer
' year counter
output As String
' amount after each year
Perform calculation to
Append year followed by the formatted
principal = 1000.00
determine
amount
in
account
rate = 0.05
calculation result and newline character
to
end of String output
output = "Year" & vbTab & "Amount on deposit" & vbCrLf
' calculate amount after each year
For year = 1 To 10
amount = principal * (1 + rate) ^ year
output &= year & vbTab & _
String.Format("{0:C}", amount) & vbCrLf
Next
' display output
MessageBox.Show(output, "Compound Interest", _
MessageBoxButtons.Ok, Specify
MessageBoxIcon.Information)
C (for “currency”) as
End Sub ' Main
formatting code
End Module ' modInterest
 2002 Prentice Hall.
All rights reserved.
13
Outline
Program Output
 2002 Prentice Hall.
All rights reserved.
14
5.4 Examples Using the For/Next Structure
Forma t C od e
De sc rip tio n
C
Currency. Precedes the number with $, separates every three digits
with commas and sets the number of decimal places to two.
E
Scientific notation. Displays one digit to the left of the decimal and
six digits to the right of the decimal, followed by the character E and
a three-digit integer representing the exponent of a power of 10. For
example, 956.2 is formatted a 9.562000E+002..
Fixed point. Sets the number of decimal places to two.
F
G
General. Visual Basic chooses either E or F for you, depending on
which representation generates a shorter string.
D
Decimal. Displays an integer as a whole number in standard base-10
format.
N
Number. Separates every three digits with a comma and sets the
number of decimal places to two.
X
Hexadecimal integer. Displays the integer in hexadecimal (base-16)
notation. We discuss hexidecimal notation in Appendix B.
Fig. 5.9
String form a tting c od es.
Fig. 5.9
 2002 Prentice Hall. All rights reserved.
String formatting codes.
5.5 Select Case Multiple-Selection
Structure
• Multiple-Selection Structure
– Tests expression separately for each value expression may
assume
– Select Case keywords begin structure
• Followed by controlling expression
– Compared sequentially with each case
– Code in case executes if match is found
– Program control proceeds to first statement after structure
• Case keyword
– Specifies each value to test for
– Followed by code to execute if test is true
– Case Else
• Optional
• Executes if no match is found
• Must be last case in sequence
 2002 Prentice Hall. All rights reserved.
15
16
1 ' Fig. 5.10: SelectTest.vb
2 ' Using the Select Case structure.
3
4 Module modEnterGrades
5
6
Sub Main()
7
Dim grade As Integer = 0 ' one grade
8
Dim aCount As Integer = 0 ' number of As
9
Dim bCount As Integer = 0 ' number of Bs
10
Dim cCount As Integer = 0 ' number of Cs
11
Dim dCount As Integer = 0 ' number of Ds
12
Dim fCount As Integer = 0 ' number of Fs
Select
Case begins
13
multiple-selection
structure a grade, -1 to quit: ")
14
Console.Write("Enter
Controlling
expression
15
grade = Console.ReadLine()
First Case executes if
16
grade is exactly 100
17
' input and process grades
18
While grade <> -1
Next Case executes if grade is
19
20
Select Case grade
check
which
was input
between' 90
and 99,
the grade
range being
21
specified with the To keyword
22
Case 100
' student scored 100
23
Console.WriteLine("Perfect Score!" & vbCrLf & _
24
"Letter grade: A" & vbCrLf)
25
aCount += 1
26
27
Case 90 To 99
' student scored 90-99
28
Console.WriteLine("Letter Grade: A" & vbCrLf)
29
aCount += 1
30
31
Case 80 To 89
' student scored 80-89
32
Console.WriteLine("Letter Grade: B" & vbCrLf)
33
bCount += 1
34
Outline
SelectTest.vb
 2002 Prentice Hall.
All rights reserved.
17
35
Case 70 To 79
' student scored 70-79
36
Console.WriteLine("Letter Grade: C" & vbCrLf)
37
cCount += 1
38
39
Case 60 To 69
' student scored 60-69
40
Console.WriteLine("Letter Grade: D" & vbCrLf)
41Optional Case Else
dCount
+= 1if no match
executes
42
occurs with previous Cases
43
' student scored 0 or 10-59 (10 points for attendance)
44
Case 0, 10 To 59
45
Console.WriteLine("Letter Grade: F" & vbCrLf)
46
fCount += 1
End Select marks
47
48
Case Else
end of structure
49
50
' alert user that invalid grade was entered
51
Console.WriteLine("Invalid Input. " & _
52
"Please enter a valid grade." & vbCrLf)
53
End Select
54
55
Console.Write("Enter a grade, -1 to quit: ")
56
grade = Console.ReadLine()
57
End While
58
59
' display count of each letter grade
60
Console.WriteLine(vbCrLf & _
61
"Totals for each letter grade are: " & vbCrLf & _
62
"A: " & aCount & vbCrLf & "B: " & bCount _
63
& vbCrLf & "C: " & cCount & vbCrLf & "D: " & _
64
dCount & vbCrLf & "F: " & fCount)
65
66
End Sub ' Main
67
68
End Module ' modEnterGrades
Outline
SelectTest.vb
 2002 Prentice Hall.
All rights reserved.
Enter a grade: 84
Letter Grade: B
Enter a grade: 100
Perfect Score!
Letter grade : A+
18
Outline
Program Output
Enter a grade: 7
Invalid Input. Please enter a valid grade.
Enter a grade: 95
Letter Grade: A
Enter a grade: 78
Letter Grade: C
Totals for each letter grade are:
A: 2
B: 1
C: 1
D: 0
F: 0
 2002 Prentice Hall.
All rights reserved.
19
5.5 Select Case Multiple
Case a
true
Case a action(s)
true
Case b action(s)
true
Case z action(s)
false
Case b
false
.
.
.
Case z
false
Case Else action(s)
Fig. 5.11 Flowcharting the Select Case multiple-selection structure.
 2002 Prentice Hall. All rights reserved.
20
5.6 Do/Loop While Repetition Structure
• Do/Loop While Repetition Structure
– Similar to While and Do/While
– Loop-continuation condition tested after body executes
• Loop body always executed at least once
– Begins with keyword Do
– Ends with keywords Loop While followed by condition
 2002 Prentice Hall. All rights reserved.
21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
' Fig. 5.12: DoWhile.vb
' Demonstrating the Do/Loop While repetition structure.
Module modDoWhile
Outline
DoWhile.vb
Sub Main()
Dim
Do keyword
Loop While
Condition tested
structure
counter begins
As Integer
= 1
ends
structure
after body executes
' print values 1 to 5
Do
Console.Write(counter & " ")
counter += 1
Loop While (counter <= 5)
End Sub ' Main
End Module ' modDoWhile
1 2 3 4 5
Program Output
 2002 Prentice Hall.
All rights reserved.
22
5.7 Do/Loop Until Repetition Structure
action(s)
true
condition
false
Fig. 5.13 Flowcharting the Do/Loop While repetition structure.
 2002 Prentice Hall. All rights reserved.
23
5.7 Do/Loop Until Repetition Structure
• Do/Loop Until Repetition Structure
– Similar to Do Until/Loop structure
– Loop-continuation condition tested after body executes
• Loop body always executed at least once
 2002 Prentice Hall. All rights reserved.
24
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
' Fig. 5.14: LoopUntil.vb
' Using Do/Loop Until repetition structure
Module modLoopUntil
Sub Main()
Dim counter As Integer
Outline
LoopUntil.vb
Condition tested
= 1 body executes
after
' print values 1 to 5
Do
Console.Write(counter & " ")
counter += 1
Loop Until counter > 5
End Sub ' Main
End Module ' modLoopUntil
1 2 3 4 5 6 7 8 9
Program Output
 2002 Prentice Hall.
All rights reserved.
25
5.7 Do/Loop Until Repetition Structure
action(s)
false
condition
true
Fig. 5.15 Flowcharting the Do/Loop Until repetition structure.
 2002 Prentice Hall. All rights reserved.
5.8 Using the Exit Keyword in a Repetition
Structure
• Exit Statements
– Alter the flow of control
• Cause immediate exit from a repetition structure
– Exit Do
• Executed in Do structures
– Exit For
• Executed in For structures
– Exit While
• Executed in While structures
 2002 Prentice Hall. All rights reserved.
26
27
1 ' Fig. 5.16: ExitTest.vb
2 ' Using the Exit keyword in repetition structures.
3
4
Imports System.Windows.Forms
5
Loop specified to
6
Module modExitTest
7
execute
10 times
Exit For
statement
8
Sub Main()
Program
control
executes when
condition
is proceeds
9
Dim output As String
firsttostatement
after the
10
Dim counter As Integer
met, causingtoloop
exit
11
structure
12
For counter = 1 To 10
13
14
' skip remaining code in loop only if counter = 3
15
If counter = 3 Then
counter is 3 when loop
16
Exit For
starts, specified to execute
17
End If
18
until it is greater than 10
19
Next
Exit Do executes when counter
20
21
output = "counter =is"5,&causing
counterloop
& _to exit
22
" after exiting For/Next structure" & vbCrLf
23
24
Do Until counter > 10
25
26
' skip remaining code in loop only if counter = 5
27
If counter = 5 Then
28
Exit Do
29
End If
30
31
counter += 1
32
Loop
33
Outline
ExitTest.vb
 2002 Prentice Hall.
All rights reserved.
28
34
output &= "counter = " & counter & _
is &5 when
loop
35
" after exiting Do Until/Loop counter
structure"
vbCrLf
36
starts, specified to execute
37
While counter <= 10
while less than or equal to 10
38
39
' skip remaining code in loop only if counter = 7
40
If counter = 7 Then
41
Exit While
42
End If
Exit While executes when
43
counter is 7, causing loop to
44
counter += 1
45
End While
exit
46
47
output &= "counter = " & counter & _
48
" after exiting While structure"
49
50
MessageBox.Show(output, "Exit Test", _
51
MessageBoxButtons.OK, MessageBoxIcon.Information)
52
End Sub ' Main
53
54 End Module ' modExitTest
Outline
Program Output
 2002 Prentice Hall.
All rights reserved.
29
5.9 Logical Operators
• Used to form complex conditions by combining
simple ones
– Short-circuit evaluation
• Execute only until truth or falsity is known
– AndAlso operator
• Returns true if and only if both conditions are true
– OrElse operator
• Returns true if either or both of two conditions are true
 2002 Prentice Hall. All rights reserved.
30
5.9 Logical Operators (II)
• Logical Operators without short-circuit evaluation
– And and Or
• Similar to AndAlso and OrElse respectively
• Always execute both of their operands
• Used when an operand has a side effect
– Condition makes a modification to a variable
– Should be avoided to reduce subtle errors
– Xor
• Returns true if and only if one operand is true and the other
false
 2002 Prentice Hall. All rights reserved.
31
5.9 Logical Operators (III)
• Logical Negation
– Not
• Used to reverse the meaning of a condition
• Unary operator
– Requires one operand
• Can usually be avoided by expressing a condition differently
 2002 Prentice Hall. All rights reserved.
32
5.9 Logical Operators
exp ression1
exp ression2
exp ression1 AndAlso
exp ression2
False
False
False
False
True
True
True
False
True
False
False
True
Fig. 5.17
Truth ta b le fo r the
AndAlso (log ic a l AND) op era tor.
Fig. 5.17 Truth table for the AndAlso (logical AND) operator.
 2002 Prentice Hall. All rights reserved.
33
5.9 Logical Operators
exp ression1
exp ression2
exp ression1 OrElse exp ressio n2
False
False
False
False
True
True
True
False
True
True
True
True
Fig. 5.18
Truth ta b le fo r the
OrElse (lo g ic a l OR) op era tor.
Fig. 5.18 Truth table for the OrElse (logical OR) operator.
 2002 Prentice Hall. All rights reserved.
34
5.9 Logical Operators
exp ression1
exp ression2
exp ression1 Xor exp re ssio n2
False
False
False
False
True
True
True
False
True
True
True
False
Fig. 5.19
Truth ta b le fo r the b oo lea n log ic a l e xc lusive OR ( Xor) op e ra to r.
Fig. 5.19 Truth table for the boolean logical exclusive OR (Xor) operator.
exp ression
Not exp ression
False
True
True
False
Fig. 5.20
Truth ta b le fo r op e ra to r Not (lo g ic a l NOT).
Fig. 5.20 Truth table for operator Not (logical NOT).
 2002 Prentice Hall. All rights reserved.
35
Outline
Program Output
 2002 Prentice Hall.
All rights reserved.
36
5.9 Logical Operators
Op era tors
Assoc ia tivity
Typ e
()
left to right
parentheses
^
left to right
exponentiation
+ -
left to right
unary prefix
* /
left to right
multiplicative
\
left to right
Integer division
Mod
left to right
modulus
+ -
left to right
additive
&
left to right
concatenation
< <= > >= = <>
left to right
relational and equality
Not
And AndAlso
Or OrElse
Xor
left to right
logical NOT
left to right
boolean logical AND
left to right
boolean logical inclusive OR
left to right
boolean logical exclusive OR
Fig. 5.22
Prec ed e nc e a nd a ssoc ia tivity of the op e ra tors d isc ussed so fa r.
Fig. 5.22 Precedence and associativity of the operators discussed so far.
 2002 Prentice Hall. All rights reserved.
Download