control structures: part 2. introduction essentials of counter-controlled repetition for / next...

50
Control Control Structures: Part 2 Structures: Part 2

Post on 20-Dec-2015

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Control Structures: Part 2Control Structures: Part 2

Page 2: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

IntroductionEssentials of Counter-Controlled RepetitionFor/Next Repetition StructureExamples Using the For/Next StructureSelect Case Multiple-Selection StructureDo/Loop While Repetition StructureDo/Loop Until Repetition StructureUsing the Exit Keyword in a Repetition StructureLogical OperatorsStructured Programming Summary

OutlineOutline

Page 3: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next 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:

For/NextFor/Next Repetition Structure Repetition Structure

Page 4: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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 ' modForCounter2 4 6 8 10

Control variable initialized to 2

Step increments counter by 2 each iteration

Next marks end of loop

Page 5: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

ForFor//NextNext Repetition Structure 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

Page 6: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

ForFor//NextNext Repetition Structure 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

Page 7: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Examples Using the Examples Using the ForFor//NextNext Structure 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

Page 8: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Program to sum the even integers from 2 to 100.

Page 9: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Examples Using the For/Next StructureMessageBoxIcon 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.

Page 10: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure 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.

Examples Using the For/Next Structure

Page 11: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

The next example computes compound interest using the The next example computes compound interest using the For/Next structure. Consider the following problem For/Next structure. Consider the following problem statement:statement:

A person invests $1000.00 in a savings account that A person invests $1000.00 in a savings account that yields 5% interest. Assuming that all interest is left on yields 5% interest. Assuming that all interest is left on deposit, calculate and print the amount of money in deposit, calculate and print the amount of money in

the the account at the end of each year over a period of 10 account at the end of each year over a period of 10 years. years. To determine these amounts, use the following To determine these amounts, use the following formula:formula:

a = p (1 + r) n a = p (1 + r) n wherewhere

p p is the original amount invested (i.e., the principal)is the original amount invested (i.e., the principal)r r is the annual interest rate (e.g., .05 stands for 5%)is the annual interest rate (e.g., .05 stands for 5%)n n is the number of yearsis the number of yearsa a is the amount on deposit at the end of the is the amount on deposit at the end of the nnth year.th year.

Examples Using the For/Next Structure

Page 12: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Type Decimal used for precise monetary calculations

Specify C (for “currency”) as formatting code

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

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

Page 13: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Program OutputProgram Output

Page 14: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Format 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.

Examples Using the For/Next Structure

Page 15: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Page 16: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next 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, 80–89 is a B, 70–79 is a C, 60–69 is a D and 0–

59 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.

Select Case Multiple-Selection Structure

Page 17: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure
Page 18: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Optional Case Else executes if no match occurs with previous Cases

Required End Select marks end of structure

Page 19: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Program Output

Page 20: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next 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

Page 21: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Select Case Multiple-Selection Structure

Page 22: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next 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

Page 23: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Do/Loop While Repetition Structure

Page 24: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

true

false

condition

action(s)

Do/Loop While Repetition Structure

Page 25: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next 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

Page 26: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Condition tested after body executes

Print the numbers from 1–5.

Page 27: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

true

falsecondition

action(s)

Do/Loop Until Repetition Structure

Page 28: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Using the Using the ExitExit Keyword in a Keyword in a Repetition StructureRepetition 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

Page 29: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Page 30: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure
Page 31: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Program Output

Page 32: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

• 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 OperatorsLogical Operators

Page 33: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Page 34: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Page 35: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

• 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 variable’s 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 statements—the 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 OperatorsLogical Operators

Page 36: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

Page 37: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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.

Page 38: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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.

Page 39: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Logical Operatorsexpression1 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).

Page 40: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure
Page 41: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure
Page 42: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Program Output

Page 43: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Logical OperatorsLogical 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.

Page 44: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Structured Programming SummaryStructured 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

Page 45: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Structured Programming SummaryStructured 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)

Page 46: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Structured Programming SummaryStructured 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

Page 47: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

Structured Programming SummaryStructured 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

Page 48: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

ConclusionConclusion

• The The ForFor//Next Next repetition structure handles the details repetition structure handles the details of counter-controlled repetition. The required of counter-controlled repetition. The required To To keyword specifies the initial value and the final value keyword specifies the initial value and the final value of the control variable. The optional of the control variable. The optional Step Step keyword keyword specifies the increment.specifies the increment.

• When supplying four arguments to method When supplying four arguments to method MessageBox.ShowMessageBox.Show, the first two arguments are , the first two arguments are strings displayed in the dialog and the dialog’s title strings displayed in the dialog and the dialog’s title bar. The third and fourth arguments are constants bar. The third and fourth arguments are constants representing buttons and icons, respectively.representing buttons and icons, respectively.

Page 49: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

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

ConclusionConclusion

Page 50: Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure

• 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).

ConclusionConclusion