5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction...
-
Upload
tyler-holmes -
Category
Documents
-
view
223 -
download
0
description
Transcript of 5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction...
5.1 Introduction
• Problem Solving– Requires understanding of:
• Building blocks• Program-construction principles
BZUPAGES.COM
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
BZUPAGES.COM
WhileCounter.vb
1 ' Fig. 5.1: WhileCounter.vb2 ' Using the While structure to demonstrate counter-controlled 3 ' repetition.4 5 Module modWhileCounter6 7 Sub Main()8 9 Dim counter As Integer = 2 ' initialization10 11 While (counter <= 10) ' repetition condition12 Console.Write(counter & " ")13 counter += 2 ' increment counter14 End While15 16 End Sub ' Main1718 End Module ' modWhileCounter
2 4 6 8 10
While structure used for repetition
Control variable defined and initialized to 2
Control variable incremented by 2 each iteration
Condition tests if control variable is less than or equal to final value
BZUPAGES.COM
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
BZUPAGES.COM
ForCounter.vb
Program Output
1 ' Fig. 5.2: ForCounter.vb2 ' Using the For/Next structure to demonstrate counter-controlled 3 ' repetition.4 5 Module modForCounter6 7 Sub Main()8 Dim counter As Integer910 ' initialization, repetition condition and11 ' incrementing are included in For structure12 For counter = 2 To 10 Step 213 Console.Write(counter & " ")14 Next1516 End Sub ' Main1718 End Module ' modForCounter
2 4 6 8 10
Control variable initialized to 2To specifies
final value of 10Step increments counter by 2 each iteration
Next marks end of loop
BZUPAGES.COM
5.3 For/Next Repetition Structure
Fig. 5.3 Components of a typical For/Next header.
For counter = 2 To 10 Step 2
For keyword
Initial value of control variable
Final value of control variable Increment of
control variable
Control variable name
To keyword
Step keyword
BZUPAGES.COM
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
BZUPAGES.COM
5.4 Examples Using the For/Next Structure
Fig. 5.4 Flowcharting a typical For/Next repetition structure.
counter = 1
counter < = 10 (implicit)
false
true Console.WriteLine(counter * 10)
counter += 1 (implicit)
Establish initial value of control
variable
Determine if final value of
control variable has been reached
Body of loop (this can be multiple
statements)
Increment the control variable
BZUPAGES.COM
Sum.vb
Program Output
1 ' Fig. 5.5: Sum.vb2 ' Using For/Next structure to demonstrate summation.3 4 Imports System.Windows.Forms5 6 Module modSum7 8 Sub Main()9 10 Dim sum = 0, number As Integer11 12 ' add even numbers from 2 to 10013 For number = 2 To 100 Step 214 sum += number15 Next16 17 MessageBox.Show("The sum is " & sum, _18 "Sum even integers from 2 to 100", _19 MessageBoxButtons.OK, MessageBoxIcon.Information)20 End Sub ' Main21 22 End Module ' modSum
Control variable counts by 2, from 2 to 100Value of number is added in
each iteration to determine sum of even numbers Text displayed
in dialogDisplay a MessageBox
Indicate button to be OK button
Indicate icon to be Information icon
Text displayed in title bar
BZUPAGES.COM
5.4 Examples Using the For/Next Structure
MessageBoxIcon Constants Icon Description 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.
MessageBoxIcon.Error Icon containing an in a red circle. Typically used to alert the user of errors or critical situations.
Fig. 5.6 Icons for message dialogs.
BZUPAGES.COM
5.4 Examples Using the For/Next Structure
MessageBoxButton constants Description 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- Ignore
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..
Fig. 5.7 Button constants for message dialogs.
Fig. 5.7 Button constants for message dialogs.
BZUPAGES.COM
Interest.vb
1 ' Fig. 5.8: Interest.vb2 ' Calculating compound interest.3 4 Imports System.Windows.Forms5 6 Module modInterest7 8 Sub Main()9 10 Dim amount, principal As Decimal ' dollar amounts11 Dim rate As Double ' interest rate12 Dim year As Integer ' year counter13 Dim output As String ' amount after each year14 15 principal = 1000.0016 rate = 0.0517 18 output = "Year" & vbTab & "Amount on deposit" & vbCrLf19 20 ' calculate amount after each year21 For year = 1 To 1022 amount = principal * (1 + rate) ^ year23 output &= year & vbTab & _24 String.Format("{0:C}", amount) & vbCrLf25 Next26 27 ' display output28 MessageBox.Show(output, "Compound Interest", _29 MessageBoxButtons.Ok, MessageBoxIcon.Information)30 31 End Sub ' Main32 33 End Module ' modInterest
Perform calculation to determine amount in account
Append year followed by the formatted calculation result and newline character to end of String output
Specify C (for “currency”) as formatting code
Type Decimal used for precise monetary calculations
BZUPAGES.COM
Program Output
BZUPAGES.COM
5.4 Examples Using the For/Next StructureFormat Code Description
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..
F Fixed point. Sets the number of decimal places to two. 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 formatting codes.
Fig. 5.9 String formatting codes. BZUPAGES.COM
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
BZUPAGES.COM
SelectTest.vb
1 ' Fig. 5.10: SelectTest.vb2 ' Using the Select Case structure.3 4 Module modEnterGrades5 6 Sub Main()7 Dim grade As Integer = 0 ' one grade8 Dim aCount As Integer = 0 ' number of As9 Dim bCount As Integer = 0 ' number of Bs10 Dim cCount As Integer = 0 ' number of Cs11 Dim dCount As Integer = 0 ' number of Ds12 Dim fCount As Integer = 0 ' number of Fs13 14 Console.Write("Enter a grade, -1 to quit: ")15 grade = Console.ReadLine()16 17 ' input and process grades18 While grade <> -119 20 Select Case grade ' check which grade was input21 22 Case 100 ' student scored 10023 Console.WriteLine("Perfect Score!" & vbCrLf & _24 "Letter grade: A" & vbCrLf)25 aCount += 126 27 Case 90 To 99 ' student scored 90-9928 Console.WriteLine("Letter Grade: A" & vbCrLf)29 aCount += 130 31 Case 80 To 89 ' student scored 80-8932 Console.WriteLine("Letter Grade: B" & vbCrLf)33 bCount += 134
Select Case begins multiple-selection structure
Controlling expressionFirst Case executes if grade is exactly 100
Next Case executes if grade is between 90 and 99, the range being specified with the To keyword
BZUPAGES.COM
SelectTest.vb
35 Case 70 To 79 ' student scored 70-7936 Console.WriteLine("Letter Grade: C" & vbCrLf)37 cCount += 138 39 Case 60 To 69 ' student scored 60-6940 Console.WriteLine("Letter Grade: D" & vbCrLf)41 dCount += 142 43 ' student scored 0 or 10-59 (10 points for attendance)44 Case 0, 10 To 5945 Console.WriteLine("Letter Grade: F" & vbCrLf)46 fCount += 147 48 Case Else49 50 ' alert user that invalid grade was entered51 Console.WriteLine("Invalid Input. " & _52 "Please enter a valid grade." & vbCrLf)53 End Select54 55 Console.Write("Enter a grade, -1 to quit: ")56 grade = Console.ReadLine()57 End While58 59 ' display count of each letter grade60 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 ' Main67 68 End Module ' modEnterGrades
Optional Case Else executes if no match occurs with previous Cases
End Select marks end of structure
BZUPAGES.COM
Program Output
Enter a grade: 84Letter Grade: B Enter a grade: 100Perfect Score!Letter grade : A+ Enter a grade: 7Invalid Input. Please enter a valid grade. Enter a grade: 95Letter Grade: A Enter a grade: 78Letter Grade: C Totals for each letter grade are:A: 2B: 1C: 1D: 0F: 0
BZUPAGES.COM
5.5 Select Case Multiple
Fig. 5.11 Flowcharting the Select Case multiple-selection structure.
Case a
Case b
Case z
.
.
.
Case Else action(s)
false
false
false
Case a action(s)
Case b action(s)
Case z action(s)
true
true
true
BZUPAGES.COM
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
BZUPAGES.COM
DoWhile.vb
Program Output
1 ' Fig. 5.12: DoWhile.vb2 ' Demonstrating the Do/Loop While repetition structure.3 4 Module modDoWhile5 6 Sub Main()7 8 Dim counter As Integer = 19 10 ' print values 1 to 511 Do 12 Console.Write(counter & " ")13 counter += 114 Loop While (counter <= 5)15 16 End Sub ' Main1718 End Module ' modDoWhile
1 2 3 4 5
Do keyword begins structure
Loop While ends structureCondition tested
after body executes
BZUPAGES.COM
5.7 Do/Loop Until Repetition Structure
Fig. 5.13 Flowcharting the Do/Loop While repetition structure.
true
false
condition
action(s)
BZUPAGES.COM
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
BZUPAGES.COM
LoopUntil.vb
Program Output
1 ' Fig. 5.14: LoopUntil.vb2 ' Using Do/Loop Until repetition structure3 4 Module modLoopUntil5 6 Sub Main()7 8 Dim counter As Integer = 19 10 ' print values 1 to 511 Do12 Console.Write(counter & " ")13 counter += 114 Loop Until counter > 515 16 End Sub ' Main1718 End Module ' modLoopUntil
1 2 3 4 5 6 7 8 9
Condition tested after body executes
BZUPAGES.COM
5.7 Do/Loop Until Repetition Structure
Fig. 5.15 Flowcharting the Do/Loop Until repetition structure.
true
falsecondition
action(s)
BZUPAGES.COM
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
BZUPAGES.COM
ExitTest.vb
1 ' Fig. 5.16: ExitTest.vb2 ' Using the Exit keyword in repetition structures.3 4 Imports System.Windows.Forms5 6 Module modExitTest7 8 Sub Main()9 Dim output As String10 Dim counter As Integer11 12 For counter = 1 To 1013 14 ' skip remaining code in loop only if counter = 315 If counter = 3 Then16 Exit For17 End If18 19 Next20 21 output = "counter = " & counter & _22 " after exiting For/Next structure" & vbCrLf23 24 Do Until counter > 1025 26 ' skip remaining code in loop only if counter = 527 If counter = 5 Then28 Exit Do29 End If30 31 counter += 132 Loop33
Loop specified to execute 10 timesExit For statement
executes when condition is met, causing loop to exit
Program control proceeds to first statement after the structure
counter is 3 when loop starts, specified to execute until it is greater than 10
Exit Do executes when counter is 5, causing loop to exit
BZUPAGES.COM
Program Output
34 output &= "counter = " & counter & _35 " after exiting Do Until/Loop structure" & vbCrLf36 37 While counter <= 1038 39 ' skip remaining code in loop only if counter = 740 If counter = 7 Then41 Exit While42 End If43 44 counter += 145 End While46 47 output &= "counter = " & counter & _48 " after exiting While structure"49 50 MessageBox.Show(output, "Exit Test", _51 MessageBoxButtons.OK, MessageBoxIcon.Information)52 End Sub ' Main53 54 End Module ' modExitTest
counter is 5 when loop starts, specified to execute while less than or equal to 10
Exit While executes when counter is 7, causing loop to exit
BZUPAGES.COM
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
BZUPAGES.COM
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
BZUPAGES.COM
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
BZUPAGES.COM
5.9 Logical Operators
expression1 expression2 expression1 AndAlso expression2
False False False
False True False True False False True True True Fig. 5.17 Truth table for the AndAlso (logical AND) operator.
Fig. 5.17 Truth table for the AndAlso (logical AND) operator.
BZUPAGES.COM
5.9 Logical Operators
expression1 expression2 expression1 OrElse expression2 False False False
False True True True False True True True True Fig. 5.18 Truth table for the OrElse (logical OR) operator.
Fig. 5.18 Truth table for the OrElse (logical OR) operator.
BZUPAGES.COM
5.9 Logical Operators
expression1 expression2 expression1 Xor expression2 False False False
False True True True False True True True False Fig. 5.19 Truth table for the boolean logical exclusive OR (Xor) operator.
Fig. 5.19 Truth table for the boolean logical exclusive OR (Xor) operator.
expression Not expression False True
True False Fig. 5.20 Truth table for operator Not (logical NOT).
Fig. 5.20 Truth table for operator Not (logical NOT).
BZUPAGES.COM
5.9 Logical OperatorsOperators Associativity Type () 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 left to right logical NOT
And AndAlso left to right boolean logical AND
Or OrElse left to right boolean logical inclusive OR
Xor left to right boolean logical exclusive OR
Fig. 5.22 Precedence and associativity of the operators discussed so far.
Fig. 5.22 Precedence and associativity of the operators discussed so far.BZUPAGES.COM
5.10 Structured Programming Summary
• Structured Programming– Promotes simplicity– Produces programs that are easier to understand, test, debug
and modify– Rules for Forming Structured Programs
• If followed, an unstructured flowchart cannot be created– Only three forms of control needed
• Sequence• Selection
– If/Then structure sufficient to provide any form of selection
• Repetition– While structure sufficient to provide any form of
repetition
BZUPAGES.COM
5.10 Structured Programming Summary
Fig. 5.23 Visual Basic’s single-entry/single-exit sequence and selection structures.
Sequence
...
Selection
If/Then structure (single selection)
T
F
If/Then/Else structure (double selection)
TF
...
Select Case structure (multiple selection)
BZUPAGES.COM
5.10 Structured Programming Summary
Fig. 5.24 Visual Basic’s single-entry/single-exit repetition structures.
While structure
T
F
F
T
For/Next structure
T
F
Do/Loop Until structure Do/Loop While structure
F
T
Repetition
BZUPAGES.COM
5.10 Structured Programming Summary
Fig. 5.24 Visual Basic’s single-entry/single-exit repetition structures.
Do While/Loop structure
T
F
Do Until/Loop structure
F
T
F
T
For Each/Next structure
Repetition
BZUPAGES.COM