Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 – Control Structures: Part 2

Similar presentations


Presentation on theme: "Chapter 5 – Control Structures: Part 2"— Presentation transcript:

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 5.10   Structured Programming Summary

2 5.1 Introduction Problem Solving Requires understanding of:
Building blocks Program-construction principles

3 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

4 Control variable defined and initialized to 2 WhileCounter.vb
1 ' Fig. 5.1: WhileCounter.vb 2 ' Using the While structure to demonstrate counter-controlled 3 ' repetition. 4 5 Module modWhileCounter 6 Sub Main() 8 Dim counter As Integer = 2 ' initialization 10 While (counter <= 10) ' repetition condition Console.Write(counter & " ") counter += 2 ' increment counter End While 15 End Sub ' Main 17 18 End Module ' modWhileCounter Control variable defined and initialized to 2 WhileCounter.vb While structure used for repetition Condition tests if control variable is less than or equal to final value Control variable incremented by 2 each iteration

5 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

6 ForCounter.vb Program Output
1 ' Fig. 5.2: ForCounter.vb 2 ' Using the For/Next structure to demonstrate counter-controlled 3 ' repetition. 4 5 Module modForCounter 6 Sub Main() Dim counter As Integer 9 ' initialization, repetition condition and ' incrementing are included in For structure For counter = 2 To 10 Step 2 Console.Write(counter & " ") Next 15 End Sub ' Main 17 18 End Module ' modForCounter Control variable initialized to 2 ForCounter.vb Program Output To specifies final value of 10 Step increments counter by 2 each iteration Next marks end of loop Try by using step 0 Try from 4 to-2 step2

7 5.3 For/Next Repetition Structure
Final value of control variable Initial 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.

8 5.4 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

9 5.4 Examples Using the For/Next 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 Fig. 5.4 Flowcharting a typical For/Next repetition structure.

10 Control variable counts by 2, from 2 to 100 Sum.vb Program Output
1 ' Fig. 5.5: Sum.vb 2 ' Using For/Next structure to demonstrate summation. 3 4 Imports System.Windows.Forms 5 6 Module modSum 7 Sub Main() 9 Dim sum = 0, number As Integer 11 ' add even numbers from 2 to 100 For number = 2 To 100 Step 2 sum += number Next 16 MessageBox.Show("The sum is " & sum, _ "Sum even integers from 2 to 100", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 21 22 End Module ' modSum Control variable counts by 2, from 2 to 100 Sum.vb Program Output Value of number is added in each iteration to determine sum of even numbers Text displayed in dialog Display a MessageBox Text displayed in title bar Indicate button to be OK button Indicate icon to be Information icon

11 5.4 Examples Using the For/Next Structure
Fig. 5.6 Icons for message dialogs.

12 5.4 Examples Using the For/Next Structure
Fig. 5.7 Button constants for message dialogs.

13 Type Decimal used for precise monetary calculations
1 ' Fig. 5.8: Interest.vb 2 ' Calculating compound interest. 3 4 Imports System.Windows.Forms 5 6 Module modInterest 7 Sub Main() 9 Dim amount, principal As Decimal ' dollar amounts Dim rate As Double ' interest rate Dim year As Integer ' year counter Dim output As String ' amount after each year 14 principal = rate = 0.05 17 output = "Year" & vbTab & "Amount on deposit" & vbCrLf 19 ' 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 26 ' display output MessageBox.Show(output, "Compound Interest", _ MessageBoxButtons.Ok, MessageBoxIcon.Information) 30 End Sub ' Main 32 33 End Module ' modInterest Type Decimal used for precise monetary calculations Interest.vb 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

14 Program Output

15 5.4 Examples Using the For/Next Structure
Fig. 5.9 String formatting codes. Try them T

16 5.5 Select Case 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

17 Select Case begins multiple-selection structure
1 ' Fig. 5.10: SelectTest.vb 2 ' Using the Select Case structure. 3 4 Module modEnterGrades 5 Sub Main() Dim grade As Integer = 0 ' one grade Dim aCount As Integer = 0 ' number of As Dim bCount As Integer = 0 ' number of Bs Dim cCount As Integer = 0 ' number of Cs Dim dCount As Integer = 0 ' number of Ds Dim fCount As Integer = 0 ' number of Fs 13 Console.Write("Enter a grade, -1 to quit: ") grade = Console.ReadLine() 16 ' input and process grades While grade <> -1 19 Select Case grade ' check which grade was input 21 Case ' student scored 100 Console.WriteLine("Perfect Score!" & vbCrLf & _ "Letter grade: A" & vbCrLf) aCount += 1 26 Case 90 To ' student scored 90-99 Console.WriteLine("Letter Grade: A" & vbCrLf) aCount += 1 30 Case 80 To ' student scored 80-89 Console.WriteLine("Letter Grade: B" & vbCrLf) bCount += 1 34 SelectTest.vb Select Case begins multiple-selection structure Controlling expression First 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

18 Optional Case Else executes if no match occurs with previous Cases
Case 70 To ' student scored 70-79 Console.WriteLine("Letter Grade: C" & vbCrLf) cCount += 1 38 Case 60 To ' student scored 60-69 Console.WriteLine("Letter Grade: D" & vbCrLf) dCount += 1 42 ' student scored 0 or (10 points for attendance) Case 0, 10 To 59 Console.WriteLine("Letter Grade: F" & vbCrLf) fCount += 1 47 Case Else 49 ' alert user that invalid grade was entered Console.WriteLine("Invalid Input. " & _ "Please enter a valid grade." & vbCrLf) End Select 54 Console.Write("Enter a grade, -1 to quit: ") grade = Console.ReadLine() End While 58 ' display count of each letter grade Console.WriteLine(vbCrLf & _ "Totals for each letter grade are: " & vbCrLf & _ "A: " & aCount & vbCrLf & "B: " & bCount _ & vbCrLf & "C: " & cCount & vbCrLf & "D: " & _ dCount & vbCrLf & "F: " & fCount) 65 End Sub ' Main 67 68 End Module ' modEnterGrades SelectTest.vb Optional Case Else executes if no match occurs with previous Cases End Select marks end of structure

19 Program Output Enter a grade: 84 Letter Grade: B Enter a grade: 100
Enter a grade: 100 Perfect Score! Letter grade : A+ 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 Program Output

20 5.5 Select Case Multiple Case a Case b Case z . . . Case Else action(s) false Case a action(s) Case b action(s) Case z action(s) true Fig Flowcharting the Select Case multiple-selection structure.

21 5.6 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

22 DoWhile.vb Program Output
1 ' Fig. 5.12: DoWhile.vb 2 ' Demonstrating the Do/Loop While repetition structure. 3 4 Module modDoWhile 5 Sub Main() 7 Dim counter As Integer = 1 9 ' print values 1 to 5 Do Console.Write(counter & " ") counter += 1 Loop While (counter <= 5) 15 End Sub ' Main 17 18 End Module ' modDoWhile DoWhile.vb Program Output Do keyword begins structure Loop While ends structure Condition tested after body executes

23 5.7 Do/Loop Until Repetition Structure
action(s) condition true false Fig Flowcharting the Do/Loop While repetition structure.

24 5.7 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

25 LoopUntil.vb Program Output
1 ' Fig. 5.14: LoopUntil.vb 2 ' Using Do/Loop Until repetition structure 3 4 Module modLoopUntil 5 Sub Main() 7 Dim counter As Integer = 1 9 ' print values 1 to 5 Do Console.Write(counter & " ") counter += 1 Loop Until counter > 5 15 End Sub ' Main 17 18 End Module ' modLoopUntil LoopUntil.vb Program Output Condition tested after body executes

26 5.7 Do/Loop Until Repetition Structure
action(s) condition false true Fig Flowcharting the Do/Loop Until repetition structure.

27 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

28 Loop specified to execute 10 times
1 ' Fig. 5.16: ExitTest.vb 2 ' Using the Exit keyword in repetition structures. 3 4 Imports System.Windows.Forms 5 6 Module modExitTest 7 Sub Main() Dim output As String Dim counter As Integer 11 For counter = 1 To 10 13 ' skip remaining code in loop only if counter = 3 If counter = 3 Then Exit For End If 18 Next 20 output = "counter = " & counter & _ " after exiting For/Next structure" & vbCrLf 23 Do Until counter > 10 25 ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit Do End If 30 counter += 1 Loop 33 ExitTest.vb Loop specified to execute 10 times Exit 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

29 Exit While executes when counter is 7, causing loop to exit
output &= "counter = " & counter & _ " after exiting Do Until/Loop structure" & vbCrLf 36 While counter <= 10 38 ' skip remaining code in loop only if counter = 7 If counter = 7 Then Exit While End If 43 counter += 1 End While 46 output &= "counter = " & counter & _ " after exiting While structure" 49 MessageBox.Show(output, "Exit Test", _ MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' Main 53 54 End Module ' modExitTest counter is 5 when loop starts, specified to execute while less than or equal to 10 Program Output Exit While executes when counter is 7, causing loop to exit

30 Used to form complex conditions by combining simple ones
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

31 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

32 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

33 5.9 Logical Operators Fig Truth table for the AndAlso (logical AND) operator.

34 5.9 Logical Operators Fig Truth table for the OrElse (logical OR) operator.

35 5.9 Logical Operators Fig Truth table for the boolean logical exclusive OR (Xor) operator. Fig Truth table for operator Not (logical NOT).

36 Code generated by Visual Studio represented by this comment
1 ' Fig. 5.21: LogicalOperator.vb 2 ' Using logical operators. 3 4 Public Class FrmLogicalOperator Inherits System.Windows.Forms.Form 6 ' Visual Studio .NET generated code 8 Private Sub FrmLogicalOperator_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load 12 lblAndAlso.Text = "AndAlso" & vbCrLf & vbCrLf & _ "False AndAlso False: " & (False AndAlso False) & _ vbCrLf & "False AndAlso True: " & _ (False AndAlso True) & vbCrLf & _ "True AndAlso False: " & (True AndAlso False) & _ vbCrLf & "True AndAlso True: " & (True AndAlso True) 19 lblOrElse.Text = "OrElse" & vbCrLf & vbCrLf & _ "False OrElse False: " & (False OrElse False) & _ vbCrLf & "False OrElse True: " & (False OrElse True) & _ vbCrLf & "True OrElse False: " & (True OrElse False) & _ vbCrLf & "True OrElse True: " & (True OrElse True) 25 lblAnd.Text = "And" & vbCrLf & vbCrLf & _ "False And False: " & (False And False) & vbCrLf & _ "False And True: " & (False And True) & vbCrLf & _ "True And False: " & (True And False) & vbCrLf & _ "True And True: " & (True And True) 31 Code generated by Visual Studio represented by this comment LogicalOperator.vb Demonstrate AndAlso operator Demonstrate OrElse operator Demonstrate And operator

37 Demonstrate Or operator Demonstrate Xor operator LogicalOperator.vb
lblOr.Text = "Or" & vbCrLf & _ vbCrLf & "False Or False: " & (False Or False) & _ vbCrLf & "False Or True: " & (False Or True) & _ vbCrLf & "True Or False: " & (True Or False) & _ vbCrLf & "True Or True: " & (True Or True) 37 lblXor.Text = "Xor" & vbCrLf & _ vbCrLf & "False Xor False: " & (False Xor False) & _ vbCrLf & "False Xor True: " & (False Xor True) & _ vbCrLf & "True Xor False: " & (True Xor False) & _ vbCrLf & "True Xor True: " & (True Xor True) 43 lblNot.Text = "Not" & vbCrLf & vbCrLf & _ "Not False: " & (Not False) & vbCrLf & "Not True: " & _ (Not True) 47 End Sub ' FrmLogicalOperator_Load 49 50 End Class ' FrmLogicalOperator Demonstrate Or operator Demonstrate Xor operator LogicalOperator.vb Demonstrate Not operator

38 Program Output

39 5.9 Logical Operators Fig Precedence and associativity of the operators discussed so far.


Download ppt "Chapter 5 – Control Structures: Part 2"

Similar presentations


Ads by Google