Sie sind auf Seite 1von 50

Control Structures: Part 2

Outline
Introduction Essentials of Counter-Controlled Repetition For/Next Repetition Structure Examples Using the For/Next Structure Select Case Multiple-Selection Structure Do/Loop While Repetition Structure Do/Loop Until Repetition Structure Using the Exit Keyword in a Repetition Structure Logical Operators Structured Programming Summary

For/Next Repetition Structure


The For/Next repetition structure handles the details of counter-controlled repetition. To illustrate the power of For/Next, we now rewrite the previous program. The result is displayed in following figure:

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 Sub Main() initialized to 2 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

Step increments counter by 2 each iteration

End Module ' modForCounter

2 4 6 8 10

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

For/Next Repetition Structure


Initial value of control variable Final value of control variable

For keyword

Increment of control variable

For counter = 2 To 10 Step 2

Control variable name

To keyword

Step keyword

Fig. 5.3

Components of a typical For/Next header.

Examples Using the For/Next Structure


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 Vary the control variable over the sequence of the following values: 2, 5, 8, 11,14, 17, 20. For i = 2 To 20 Step 3 Vary the control variable over the sequence of the following values: 99, 88, 77,66, 55, 44, 33, 22, 11, 0. For i = 99 To 0 Step -11

Program to sum the even integers from 2 to 100.

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. Icon containing the letter "i." Typically used to display information about the state of the application. 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.Information

MessageBoxIcon.Question MessageBoxIcon.Error

Fig. 5.6

Icons for message dialogs.

Examples Using the For/Next Structure


Me ssa g eBoxButton c o nsta nts De sc rip tio n

MessageBoxButton.OK MessageBoxButton.OKCancel

OK button. Allows the user to acknowledge a message. Included by default. OK and Cancel buttons. Allow the user to either continue or cancel an operation. Yes and No buttons. Allow the user to respond to a question Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation. Retry and Cancel buttons. Typically used to allow the user to either retry or cancel an operation that has failed. 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..

MessageBoxButton.YesNo MessageBoxButton.YesNoCancel

MessageBoxButton.RetryCancel

MessageBoxButton.AbortRetry-

Ignore

Fig. 5.7

Button c o nsta nts for m essa g e d ia log s.

Fig. 5.7

Button constants for message dialogs.

Examples Using the For/Next Structure


The next example computes compound interest using the For/Next structure. Consider the following problem statement: A person invests $1000.00 in a savings account that yields 5% interest. Assuming that all interest is left on deposit, calculate and print the amount of money in the account at the end of each year over a period of 10 years. To determine these amounts, use the following formula: a = p (1 + r) n where p is the original amount invested (i.e., the principal) r is the annual interest rate (e.g., .05 stands for 5%) n is the number of years a is the amount on deposit at the end of the nth year.

Type Decimal used for precise monetary calculations

a tab character (vbTab) to position to the second column.

Newline character (vbCrLf) to start the next output on the next line.

Specify C (for currency) as formatting code

Program Output

Examples Using the For/Next Structure


Forma t C od e De sc rip tio n

Currency. Precedes the number with $, separates every three digits with commas and sets the number of decimal places to two. 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. General. Visual Basic chooses either E or F for you, depending on which representation generates a shorter string. Decimal. Displays an integer as a whole number in standard base-10 format. Number. Separates every three digits with a comma and sets the number of decimal places to two. Hexadecimal integer. Displays the integer in hexadecimal (base-16) notation. We discuss hexidecimal notation in Appendix B.

F G D N X Fig. 5.9

String form a tting c od es.


Fig. 5.9 String formatting codes.

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 End Select is required and marks end of structure

Select Case Multiple-Selection Structure


The following program is using a Select Case to count the number of different letter grades on an exam. Assume the exam is graded as follows: 90 and above is an A, 8089 is a B, 7079 is a C, 6069 is a D and 059 is an F. This instructor gives a minimum grade of 10 for students who were present for the exam. Students not present for the exam receive a 0.

Either 0 or any value in the range 10 to 59, inclusive matches this Case.

Optional Case Else executes if no match occurs with previous Cases

Required End Select marks end of structure

Program Output

Select Case Multiple-Selection Structure


Case statements also can use relational operators to determine whether the controlling expression satisfies a condition. For example: Case Is < 0 uses keyword Is along with the relational operator, <, to test for values less than 0. Best control to use with is the ComboBox.

Select Case Multiple-Selection Structure


Case a
false true

Case a action(s)

Case b
false . . .

true

Case b action(s)

Case z
false

true

Case z action(s)

Case Else action(s)

Fig. 5.11 Flowcharting the Select Case multiple-selection structure.

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

Do/Loop While Repetition Structure

Do/Loop While Repetition Structure

action(s)

true condition false

Fig. 5.13 Flowcharting the Do/Loop While repetition structure.

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

Print the numbers from 15.


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 = 1 ' print values 1 to 5 Do Console.Write(counter & " ") counter += 1 Loop Until counter > 5 End Sub ' Main End Module ' modLoopUntil Condition tested after body executes

1 2 3 4 5

Do/Loop Until Repetition Structure

action(s)

false condition true

Fig. 5.15 Flowcharting the Do/Loop Until repetition structure.

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 While/Loop, Do/Loop While, Do Until/Loop or Do/Loop Until structures.

Exit For
Executed in For structures

Exit While
Executed in While structures

counter is 3 when loop starts, specified to execute until it is greater than 10

Logical Operators
To handle multiple conditions more efficiently, Visual Basic provides logical operators that can be used to form complex conditions by combining simple ones. The logical operators are AndAlso, And, OrElse, Or, Xor and Not. We consider examples that use each of these operators.

Logical Operators
1. Logical operator with 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

Logical Operators
2. 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

Logical Operators
Normally, there is no compelling reason to use the And and Or operators instead of AndAlso and OrElse. However, some programmers make use of them when the right operand of a condition produces a side effect (such as a modification of a variables value) or if the right operand includes a required method call, as in the following program segment:
Console.WriteLine("How old are you?") If (gender = "F" And Console.ReadLine() >= 65) Then Console.WriteLine("You are a female senior citizen.") End If

Here, the And operator guarantees that the condition Console.ReadLine() >= 65 is evaluated, so ReadLine is called regardless of whether the overall expression is true or false. It would be better to write this code as two separate statementsthe first would store the result of Console.ReadLine() in a variable, then the second would use that variable with the AndAlso operator in the condition.

Logical Operators
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

Logical Operators

exp ression1

exp ression2

exp ression1 AndAlso exp ression2

False False True True


Fig. 5.17

False True False True


Truth ta b le fo r the

False False False True

AndAlso (log ic a l AND) op era tor.

Fig. 5.17 Truth table for the AndAlso (logical AND) operator.

Logical Operators

exp ression1

exp ression2

exp ression1 OrElse exp ressio n2

False False True True


Fig. 5.18

False True False True


Truth ta b le fo r the

False True True True

OrElse (lo g ic a l OR) op era tor.

Fig. 5.18 Truth table for the OrElse (logical OR) operator.

Logical Operators
exp ression1 exp ression2 exp ression1 Xor exp re ssio n2

False False True True


Fig. 5.19

False True False True

False True True False

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 ressio n

False True
Fig. 5.20

True False
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).

Program Output

Logical Operators
Op era tors Assoc ia tivity Typ e

() ^ + * / \

left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right left to right

parentheses exponentiation unary prefix multiplicative

Integer division
modulus additive concatenation relational and equality logical NOT boolean logical AND boolean logical inclusive OR boolean logical exclusive OR

Mod
+ & < <= > >= = <>

Not And AndAlso Or OrElse Xor


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.

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

Structured Programming Summary


Sequence If/Then structure (single selection) Selection Select Case structure (multiple selection)

T F

. . .

If/Then/Else structure (double selection)

. . .

Fig. 5.23 Visual Basics single-entry/single-exit sequence and selection structures.

Structured Programming Summary


Repetition While structure For/Next structure

T F

T F

Do/Loop Until structure

Do/Loop While structure

F T F

Fig. 5.24 Visual Basics single-entry/single-exit repetition structures.

Structured Programming Summary


Repetition Do While/Loop structure Do Until/Loop structure

T F T

For Each/Next structure

T F

Fig. 5.24 Visual Basics single-entry/single-exit repetition structures.

Conclusion
The For/Next repetition structure handles the details of counter-controlled repetition. The required To keyword specifies the initial value and the final value of the control variable. The optional Step keyword specifies the increment. When supplying four arguments to method MessageBox.Show, the first two arguments are strings displayed in the dialog and the dialogs title bar. The third and fourth arguments are constants representing buttons and icons, respectively.

Conclusion
Visual Basic provides the Select Case multipleselection structure to test a variable or expression separately for each value that the variable or expression might assume. The Select Case structure consists of a series of Case labels and an optional Case Else. Each Case contains statements to be executed if that Case is selected.

Conclusion
The logical operators are AndAlso (logical AND with short-circuit evaluation), And (logical AND without short-circuit evaluation), OrElse (logical inclusive OR with short-circuit evaluation), Or (logical inclusive OR without short-circuit evaluation), Xor (logical exclusive OR) and Not (logical NOT, also called logical negation).

Das könnte Ihnen auch gefallen