Statements: Part Pearson Education, Inc. All rights reserved.

Similar documents
Control Statements: Part Pearson Education, Inc. All rights reserved.

Control Statements: Part Pearson Education, Inc. All rights reserved.

Chapter 4 C Program Control

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 2 - Control Structures

Introduction to C Programming

C Program Control. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Control Statements. Musa M. Ameen Computer Engineering Dept.

Chapter 4 C Program Control

Chapter 2 - Control Structures

Chapter 2 - Control Structures

Programming for Engineers Iteration

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

IT 374 C# and Applications/ IT695 C# Data Structures

Functions and an Introduction to Recursion Pearson Education, Inc. All rights reserved.

بسم اهلل الرمحن الرحيم

Fundamentals of Programming Session 9

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Introduction to C# Applications

Introduction to C++ Programming Pearson Education, Inc. All rights reserved.

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

2.11 Assignment Operators. Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

C: How to Program. Week /Mar/05

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

Fundamental of Programming (C)

Chapter 3 Structured Program Development

Deeper Look Pearson Education, Inc. All rights reserved.

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Introduction to. Copyright HKTA Tang Hin Memorial Secondary School 2016

Conditionals and Loops

Microsoft Visual Basic 2005: Reloaded

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

In Fig. 3.5 and Fig. 3.7, we include some completely blank lines in the pseudocode for readability. programs into their various phases.

Unit 3. Operators. School of Science and Technology INTRODUCTION

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Functions and Recursion

CHAPTER 2.1 CONTROL STRUCTURES (SELECTION) Dr. Shady Yehia Elmashad

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

5. Selection: If and Switch Controls

Control Statements: Part 1

Repeating Instructions. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Unit 7. Lesson 7.1. Loop. For Next Statements. Introduction. Loop

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Control Statements: Part Pearson Education, Inc. All rights reserved.

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4: Control Structures I (Selection)

COMP 202 Java in one week

CS110D: PROGRAMMING LANGUAGE I

Introduction to Classes and Objects

Repetition Structures

Introduction to C# Applications Pearson Education, Inc. All rights reserved.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Course Outline. Introduction to java

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Object Oriented Programming with Visual Basic.Net

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

How to engineer a class to separate its interface from its implementation and encourage reuse.

Chapter 2: Using Data

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Fundamentals of Programming Session 25

Chapter 2, Part III Arithmetic Operators and Decision Making

Operators. Java operators are classified into three categories:

You will have mastered the material in this chapter when you can:

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

Computer Programming C++ (wg) CCOs

An overview about DroidBasic For Android

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Quick Reference Guide

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++


Fundamentals of Programming

Computer Programming C++ Classes and Objects 6 th Lecture

Introduction. C provides two styles of flow control:

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Dept. of CSE, IIT KGP

UNIT- 3 Introduction to C++

Loops / Repetition Statements. There are three loop constructs in C. Example 2: Grade of several students. Example 1: Fixing Bad Keyboard Input

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Chapter 2 - Introduction to C Programming

Control Structures (Deitel chapter 4,5)

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Computational Physics - Fortran February 1997

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Add Subtract Multiply Divide

SECTION II: LANGUAGE BASICS

Darshan Institute of Engineering & Technology for Diploma Studies

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

BRANCHING if-else statements

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

4. Inputting data or messages to a function is called passing data to the function.

Chapter 3. Selections

Transcription:

1 6 Control Statements: Part 2

2 Who can control his fate? William Shakespeare, Othello The used key is always bright. Benjamin Franklin Not everything that can be counted counts, and not every thing that counts can be counted. Albert Einstein Every advantage in the past is judged in the light of the final issue. Demosthenes

3 OBJECTIVES In this chapter you will learn: The essentials of counter-controlled controlled repetition. To use the For Next, Do Loop While and Do Loop Until repetition statements to execute statements in a program repeatedly. To perform multiple selection using the Select Case selection statement.

4 OBJECTIVES To use the Exit statement to break out of a repetition statement. To use the Continue statement to break out of the current iteration of a repetition statement. To use logical operators to form more complex conditions.

5 6.1 Introduction 6.2 Essentials of Counter-Controlled Repetition 6.3 For Next Repetition Statement 6.4 Examples Using the For Next Statement 6.5 GradeBook Case Study: Select Case Multiple-Selection Statement 66 6.6 Do Loop While Repetition i Statement 6.7 Do Loop Until Repetition Statement 6.8 Using Exit in Repetition Statements 6.9 Using Continue in Repetition Statements 6.10 Logical Operators 6.11 (Optional) Software Engineering Case Study: Identifying Objects States and Activities in the ATM System

6.2 Essentials of Counter-Controlled Repetition 6 Counter-controlled repetition requires the name of the control variable the initial value the increment (or decrement)value the condition that tests for the final value

Outline 7 The example in Fig. 6.1 uses counter-controlledcontrolled repetition to display the even integers in the range 2 10. WhileCounter.vb 1 ' Fig. 6.1: WhileCounter.vb 2 ' Using the While statement to demonstrate counter-controlled repetition. 3 Module WhileCounter 4 Sub Main() 5 Dim counter As Integer = 2 ' name and initialize loop counter 6 7 While counter <= 10 ' test final value of loop counter 8 Console.Write("{0} ", counter) 9 counter += 2 ' increment counter 10 End While 11 12 Console.WriteLine() 13 End Sub ' Main 14 End Module ' WhileCounter Initializing counter before the loop 2 4 6 8 10 Fig. 6.1 Counter-controlled repetition with the While End While statement. 2009 Pearson Education, Inc. All rights reserved.

In this For...Next statement, counter (Fig. 6.2) is used to print even numbers from 2 to 10. 1 ' Fig. 6.2: ForCounter.vb 2 ' Using the For...Next statement for counter-controlled repetition. 3 Module ForCounter 4 Sub Main() 5 ' initialization, repetition condition and 6 ' incrementing are all included in For...Next statement 7 For counter As Integer = 2 To 10 Step 2 8 Console.Write("{0} ", counter) 9 Next 10 11 Console.WriteLine() 12 End Sub ' Main 13 End Module ' ForCounter 2 4 6 8 10 Outline ForCounter.vb ( 1 of 2 ) 8 Fig. 6.2 Counter-controlled repetition with the For Next statement. Good Programming Practice 6.1 Place a blank line before and after each control statement to make it stand out in the program. 2009 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.2 Vertical spacing above and below control statements, as well as indentation of the bodies of control statements, gives programs a two-dimensional appearance that enhances readability. Error-Prevention Tip 6.1 Use a For...Next loop for counter-controlled repetition. Off-by-one errors (which occur when a loop is executed for one more or one less iteration i than is necessary) tend to disappear, because the terminating value is clear. Outline ForCounter.vb ( 2 of 2 ) 9 2009 Pearson Education, Inc. All rights reserved.

6.3 For Next Repetition Statement (Cont.) 10 The first line of the For Next statement sometimes is called the For Next header (Fig. 63) 6.3). Fig. 6.3 For...Next header components.

6.3 For Next Repetition Statement (Cont.) The general form of the For Next statement is For initializationi i i To finalvalue l Step increment statement Next A For Next statement can be represented by an equivalent While statement: initialization While variable <= finalvalue statement increment End While 11

6.3 For Next Repetition Statement (Cont.) The counter variable may be declared before the For Next statement: Dim counter As Integer For counter = 2 To 10 Step 2 Console.Write("{0} ", counter) Next Values of a For Next statement header may contain arithmetic expressions (evaluated at start). If the loop-continuation condition is initially false, the For Next s body is not performed. 12

6.3 For Next Repetition Statement (Cont.) 13 Common Programming Error 6.1 Counter-controlled loops should not be controlled with floating-point i variables. Floating-point i values are represented only approximately in the computer s memory; this can lead to imprecise counter values and inaccurate tests for termination.

6.3 For Next Repetition Statement (Cont.) 14 Error-Prevention Tip 6.2 Although the value of the control variable can be changed in the body of a For Next loop, avoid doing so, because this practice can lead to subtle errors. Common Programming Error 6.2 In nested For Next loops, the use of the same control-variable name in more than one loop is a compilation error.

6.3 For Next Repetition Statement (Cont.) 15 For counter As Integer = 1 To 10 Step 2 The activity diagram for a For Next statement (Fig. 6.4) is similar to a While statement. Fig. 6.4 For...Next repetition statement activity diagram.

6.3 For Next Repetition Statement (Cont.) 16 Local type inference infers a local variable s type based on the context of initialization. Dim x = 7 The compiler infers type Integer. Dim y = -123.45 The compiler infers type Double.

6.3 For Next Repetition Statement (Cont.) 17 For counter As Integer = 1 To 10 The preceding For Next header can now be written as: For counter = 1 To 10 In this case, counter is of type Integer because it is initialized iti with a whole number (1). Local type inference can be used on any variable that is initialized in its declaration.

The program in Fig. 6.5 uses a For...Next statement to sum the even integers from 2 to 100. Remember to add a reference to System.Windows.Forms.dll. 1 ' Fig. 6.5: Sum.vb 2 ' Using For...Next statement to demonstrate summation. 3 Imports System.Windows.Forms 4 5 Module Sum 6 Sub Main() 7 Dim sum As Integer = 0 8 9 ' add even numbers from 2 to 100 10 For number = 2 To 100 Step 2 11 sum += number 12 Next 13 14 MessageBox.Show("The sum is " & sum, _ 15 "Sum even integers from 2 to 100", _ 16 MessageBoxButtons.OK, MessageBoxIcon.Information) 17 End Sub ' Main 18 End Module ' Sum Outline Sum.vb ( 1 of 2 ) Method MessageBox.Show can take four arguments. 18 Fig. 6.5 For Next statement used for summation. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

Outline 19 Sum.vb ( 2 of 2 ) Title bar text MessageBoxIcon.Information Message text MessageBoxButtons.OK Fig. 6.5 For Next statement used for summation. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

6.4 Examples Using the For Next Statement (Cont.) 20 Method MessageBox.Show can take four arguments. The first two arguments are the text and title bar. The third argument indicates which button(s) to display. The fourth argument indicates which h icon appears.

6.4 Examples Using the For Next Statement (Cont.) 21 MessageBoxIcon constants Icon Description MessageBoxIcon.Warning or MessageBoxIcon.Exclamation Used to caution the user against potential problems. MessageBoxIcon.Information Used to display information about the state of the application. MessageBoxIcon.None No icon is displayed. MessageBoxIcon.Error Used to alert the user to errors or critical situations. Fig. 6.6 Message dialog icon constants.

6.4 Examples Using the For Next Statement (Cont.) 22 MessageBoxButton constants Description MessageBoxButtons.OK s OK button. Allows the user to acknowledge a message. Included by default. MessageBoxButtons.OKCancel MessageBoxButtons.YesNo 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. Fig. 6.7 Message dialog button constants. (Part 1 of 2.)

6.4 Examples Using the For Next Statement (Cont.) 23 MessageBoxButton constants MessageBoxButtons.YesNoCancel MessageBoxButtons.RetryCancel MessageBoxButtons.AbortRetryIgnore Description Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation. Retry and Cancel buttons. Allow the user to retry or cancel an operation that has failed. Abort, Retry and Ignore buttons. When one of a series of operations has failed, these buttons allow the user to abort the entire sequence, retry the failed operation or ignore the failed operation and continue. Fig. 6.7 Message dialog button constants. (Part 2 of 2.)

6.4 Examples Using the For Next Statement (Cont.) 24 Consider the following problem statement: A person invests $1000.00 in a savings account that yields 5% interest. Calculate the amount of money in the account at the end of each year over a period of 10 years. Use the following formula: a=p(1+r) n

1 ' Fig. 6.8: Interest.vb 2 ' Calculating compound interest. 3 Imports System.Windows.Forms 4 5 Module Interest 6 Sub Main() 7 Dim amount As Decimal ' dollar amounts on deposit 8 Dim principal As Decimal = 1000.00 ' amount invested 9 Dim rate As Double = 0.05 ' interest rate 10 11 ' amount after each year 12 Dim output As String = _ 13 "Year" & vbtab & "Amount on deposit" & vbnewline e 14 15 ' calculate amount after each year 16 For yearvalue = 1 To 10 17 amount = principal * (1 + rate) ^ yearvalue 18 output &= yearvalue & vbtab & String.Format( Format("{0:C}", amount) _ 19 & vbnewline 20 Next 21 22 ' display output 23 MessageBox.Show(output, "Compound Interest", _ 24 MessageBoxButtons.OK, MessageBoxIcon.Information) 25 End Sub ' Main 26 End Module ' Interest Outline Interest.vb ( 1 of 3 ) amount and principal are declared as type Decimal Calculating interest for each year String.Format formats text as directed 25 Fig. 6.8 For Next statement used to calculate compound interest. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

Outline 26 Interest.vb ( 2 of 3 ) Fig. 6.8 For Next statement used to calculate compound dinterest. t (Part t2 of f2) 2.) 2009 Pearson Education, Inc. All rights reserved.

Outline 27 Error-Prevention e o Tip 6.3 Do not use variables of type Single or Double to perform precise monetary calculations. The imprecision of ffloating-point i tnumbers can cause errors that tresult ltin incorrect monetary values. Use the type Decimal for monetary calculations. Interest.vb ( 3 of 3 ) Performance Tip 6.1 Avoid placing inside a loop the calculation of an expression whose value does not change each time through the loop. Such an expression should be evaluated only once and prior to the loop. 2009 Pearson Education, Inc. All rights reserved.

The GradeBook class now uses the Select...Case multiple-selection statement (Fig. 69) 6.9). 1 ' Fig. 6.9: GradeBook.vb 2 ' GradeBook class uses Select...Case statement to count letter grades. 3 Public Class GradeBook 4 Private coursenamevalue As String ' name of course 5 Private total As Integer ' sum of grades 6 Private gradecounter As Integer ' number of grades entered 7 Private acount As Integer ' count of A grades 8 Private bcount As Integer ' count of B grades 9 Private ccount As Integer ' count of C grades 10 Private dcount As Integer ' count of D grades 11 Private fcount As Integer ' count of F grades 12 Private perfectscorecount As Integer ' count of perfect scores 13 14 ' constructor initializes course name; 15 ' Integer instance variables are initialized to 0 by default 16 Public Sub New(ByVal name As String) 17 CourseName = name ' initializes CourseName 18 End Sub ' New 19 Outline GradeBook.vb ( 1 of 6 ) 28 Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and df grades. (Part t1 of f6) 6.) 2009 Pearson Education, Inc. All rights reserved.

Outline 29 20 ' property that gets and sets the course name; the Set accessor 21 ' ensures that the course name has at most 25 characters 22 Public Property CourseName() As String 23 Get ' retrieve coursenamevalue 24 Return coursenamevalue 25 End Get 26 27 Set(ByVal value As String) ' set coursenamevalue 28 If value.length <= 25 Then ' if value has 25 or fewer characters 29 coursenamevalue = value ' store the course name in the object 30 Else ' if name has more than 25 characters 31 ' set coursenamevalue to first 25 characters of parameter name 32 ' start at 0, length of 25 33 coursenamevalue = value.substring(0, 25) 34 35 Console.WriteLine( _ 36 "Course name (" & value & ") exceeds maximum length (25).") 37 Console.WriteLine( _ 38 "Limiting course name to first 25 characters." & vbnewline) 39 End If 40 End Set 41 End Property ' CourseName GradeBook.vb ( 2 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 2 of 6.) 2009 Pearson Education, Inc. All rights reserved.

Outline 30 42 43 ' display a welcome message to the GradeBook user 44 Public Sub DisplayMessage() 45 Console.WriteLine("Welcome to the grade book for " _ 46 & vbnewline & CourseName & "!" & vbnewline) 47 End Sub ' DisplayMessage 48 49 ' input arbitrary number of grades from user 50 Public Sub InputGrades() 51 Console.Write( _ 52 "Enter the grades in the range 0-100, negative value to quit: ") 53 Dim grade As Integer = Console.ReadLine() ' input first grade 54 55 ' loop until user enters a sentinel value 56 While grade >= 0 57 total += grade ' add grade to total 58 gradecounter += 1 ' increment number of grades 59 GradeBook.vb ( 3 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 3 of 6.) 2009 Pearson Education, Inc. All rights reserved.

Outline 31 60 ' call method to increment appropriate counter 61 IncrementLetterGradeCounter(grade) 62 63 ' input next grade 64 Console.Write("Enter the grades in the range 0-100, " & _ 65 "negative value to quit: ") 66 grade = Console.ReadLine() 67 End While 68 End Sub ' InputGrades 69 70 ' add 1 to appropriate counter for specified grade 71 Private Sub IncrementLetterGradeCounter(ByVal grade As Integer) 72 Select Case grade ' determine which grade was entered 73 Case 100 ' perfect score 74 perfectscorecount += 1 ' increment perfectscorecount 75 acount += 1 ' increment acount 76 Case 90 To 99 ' grade was between 90 and 99 77 acount += 1 ' increment acount GradeBook.vb ( 4 of 6 ) Using a Select...Case statement to determine which counter to increment. Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 4 of 6.) 2009 Pearson Education, Inc. All rights reserved.

Outline 32 78 Case 80 To 89 ' grade was between 80 and 89 79 bcount += 1 ' increment bcount 80 Case 70 To 79 ' grade was between 70 and 79 81 ccount += 1 ' increment ccount 82 Case 60 To 69 ' grade was between 60 and 69 83 dcount += 1 ' increment dcount 84 Case Else ' grade was less than 60 85 fcount += 1 ' increment fcount 86 End Select 87 End Sub ' IncrementLetterGradeCounter 88 89 ' display a report based on the grades entered by user 90 Public Sub DisplayGradeReport() p 91 Console.WriteLine(vbNewLine & "Grade Report:") 92 93 ' if user entered at least one grade 94 If (gradecounter > 0) Then 95 ' calculate average of all grades entered 96 Dim average As Double = total / gradecounter GradeBook.vb ( 5 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 5 of 6.) 2009 Pearson Education, Inc. All rights reserved.

Outline 33 97 98 ' output summary of results 99 Console.WriteLine("Total of the {0} grades entered is {1}", _ 100 gradecounter, total) 101 Console.WriteLine("Class average is {0:F2}", average) 102 Console.WriteLine("Number of students who received each grade:") 103 Console.WriteLine("A: " & acount) ' display number of A grades 104 Console.WriteLine( WriteLine("B: " & bcount) ' display number of B grades 105 Console.WriteLine("C: " & ccount) ' display number of C grades 106 Console.WriteLine("D: " & dcount) ' display number of D grades 107 Console.WriteLine("F: " & fcount) ' display number of F grades 108 Console.WriteLine(vbNewLine & "Number of students who " & _ 109 "received perfect scores: " & perfectscorecount) 110 Else ' no grades were entered, so output appropriate message 111 Console.WriteLine("No grades were entered") 112 End If 113 End Sub ' DisplayGradeReport 114 End Class ' GradeBook GradeBook.vb ( 6 of 6 ) Fig. 6.9 GradeBook class uses Select Case statement to count A, B, C, D and F grades. (Part 6 of 6.) 2009 Pearson Education, Inc. All rights reserved.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) Select Case grade The expression following the keywords Select Case is called the controlling expression. 34 If a matching Case is found for the controlling expression, the code in that Case executes, then program control proceeds to the first statement after the Select Case statement.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 35 Common Programming Error 6.3 Duplicate Case statements tt t are logic errors. At run time, the first matching Case is executed. Common Programming Error 6.4 If the value on the left side of the To keyword in a Case statement is larger than the value on the right side, the Case is ignored.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 36 If no match occurs between the controlling expression s s value and a Case label, the optional Case Else executes. Case Else must be the last Case. Case statements can use relational operators. Case Is < 0 Multiple values can be tested in a Case statement: Case 0, 5 To 9 The controlling expression also may be a String or Object.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 37 Error-Prevention Tip 6.4 Provide a Case Else in Select...Case statements. tt t Cases not handled in a Select...Case statement are ignored unless a Case Else is provided. The inclusion of a Case Else statement can facilitate the processing of exceptional conditions.

Module GradeBookTest (Fig. 6.10) outputs a report based on the grades entered. 1 ' Fig. 6.10: GradeBookTest.vb 2 ' Create GradeBook object, input grades and display grade report. 3 Module GradeBookTest 4 Sub Main() 5 ' create GradeBook object gradebook1 and 6 ' pass course name to constructor t 7 Dim gradebook1 As New GradeBook("CS101 Introduction to VB") 8 9 gradebook1.displaymessage() ' display welcome message 10 gradebook1.inputgrades() ' read grades from user 11 gradebook1.displaygradereport() ' display report based on grades 12 End Sub ' Main 13 End Module ' GradeBookTest Outline GradeBookTest.vb ( 1 of 2 ) 38 Fig. 6.10 GradeBookTest creates a GradeBook object and invokes its methods. (Part 1 of 2.) 2009 Pearson Education, Inc. All rights reserved.

Outline 39 Welcome to the grade book for CS101 Introduction to VB! Enter a grade in the range 0-100, negative value to quit: 99 Enter a grade in the range 0-100, negative value to quit: 92 Enter a grade in the range 0-100, negative value to quit: 45 Enter a grade in the range 0-100, negative value to quit: 57 Enter a grade in the range 0-100, negative value to quit: 63 Enter a grade in the range 0-100, negative value to quit: 71 Enter a grade in the range 0-100, negative value to quit: 76 Enter a grade in the range 0-100, negative value to quit: 85 Enter a grade in the range 0-100, negative value to quit: 90 Enter a grade in the range 0-100, negative value to quit: 100 Enter a grade in the range 0-100, negative value to quit: -1 GradeBookTest.vb ( 2 of 2 ) Grade Report: Total of the 10 grades entered is 778 Class average is 77.80 Number of students who received each grade: A: 4 B: 1 C: 2 D: 1 F: 2 Number of students who received a perfect score: 1 Fig. 6.10 GradeBookTest creates a GradeBook object and invokes its methods. (Part 2 of 2.) 2009 Pearson Education, Inc. All rights reserved.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 40 Methods declared Private can be called only by other members of the class in which the Private methods are declared. Such Private methods are commonly referred to as utility methods or helper methods.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) 41 TheWith statement allows you to make multiple references to the same object. With gradebook1.displaymessage() ' display welcome message.inputgrades() ' read grades from user.displaygradereport() ' display report based on grades End With These lines of code are collectively known as a With statement t tblock.

6.5 GradeBook Case Study: Select Case Multiple-Selection Statement (Cont.) Figure 6.11 shows the UML activity diagram for the general Select...Case statement. 42 Fig. 6.11 Select Case multiple-selection statement UML activity diagram.

The Do...Loop While repetition statement is similar to the While statement. The program in Fig. 6.12 uses a Do...Loop While statement to output the values 1 5. 1 ' Fig. 6.12: DoLoopWhile.vb 2 ' Demonstrating the Do...Loop While repetition statement. 3 Module DoLoopWhile 4 Sub Main() 5 Dim counter As Integer = 1 6 7 ' print values 1 to 5 8 Do 9 Console.Write("{0} ", counter) 10 counter += 1 11 Loop While counter <= 5 12 13 Console.WriteLine() 14 End Sub ' Main 15 End Module ' DoLoopWhile 1 2 3 4 5 Outline DoLoopWhile.vb ( 1 of 2 ) Condition tested after loop body executes 43 Fig. 6.12 Do Loop While repetition statement. 2009 Pearson Education, Inc. All rights reserved.

Outline 44 Error-Prevention Tip 6.5.Infinite loops occur when the loop-continuation condition in a While, Do While...Loop or Do...Loop While statement never becomes false. DoLoopWhile.vb ( 2 of 2 ) 2009 Pearson Education, Inc. All rights reserved.

6.6 Do Loop While Repetition Statement (Cont.) 45 The Do Loop While UML activity diagram (Fig. 6.13) illustrates that t the loop-continuation condition is not evaluated until after the statement body. Fig. 6.13 Do Loop While repetition statement activity diagram.

Figure 6.14 uses a Do...Loop Until statement to print the numbers from 1 to 5. Outline DoLoopUntil.vb 46 1 ' Fig. 6.14: DoLoopUntil.vb 2 ' Using Do...Loop Until repetition statement. 3 Module DoLoopUntil 4 Sub Main() 5 Dim counter As Integer = 1 6 7 ' print values 1 to 5 8 Do 9 Console.Write("{0} ", counter) 10 counter += 1 11 Loop Until counter > 5 12 13 Console.WriteLine() 14 End Sub ' Main 15 End Module ' DoLoopUntil 1 2 3 4 5 Condition tested after loop body executes Fig. 6.14 Do Loop Until repetition statement. 2009 Pearson Education, Inc. All rights reserved.

6.7 Do...Loop Until Repetition Statement (Cont.) Common Programming Error 6.5 Including an incorrect relational loperator or an incorrect final value for a loop counter in the condition of any repetition statement can cause off-by-one errors. 47 Error-Prevention Tip 6.6.Infinite loops occur when the loop-termination condition in a Do Until...Loop or Do...Loop Until statement never becomes true.

6.7 Do...Loop Until Repetition Statement (Cont.) Error-Prevention Tip 6.7 In a counter-controlled t dloop, ensure that t the control variable is incremented (or decremented) appropriately in the body of the loop to avoid an infinite loop. 48

6.8 Using Exit in Repetition Statements 49 An Exit statement causes the program to exit immediately from a repetition statement. The Exit Do statement can be executed in any Do statement. Exit For and Exit While cause immediate exit from For Next and While End While loops. These statements are used to alter a program s flow of control.

Figure 6.15 demonstrates Exit statements. Outline 50 1 ' Fig. 6.15: ExitTest.vb 2 ' Using the Exit statement in repetition statements. 3 Module ExitTest 4 Sub Main() 5 Dim counter As Integer ' loop counter 6 7 ' exit For...Next statement 8 For counter = 1 To 10 9 ' skip remaining code in loop only if counter = 5 10 If counter = 5 Then 11 Exit For ' break out of loop 12 End If 13 14 Console.Write("{0} ", counter) ' output counter 15 Next 16 ExitTest.vb ( 1 of 3 ) Fig. 6.15 Exit statement in repetition statements. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved.

Outline 51 17 Console.WriteLine(vbNewLine & _ 18 "Broke out of For...Next at counter = " & counter & vbnewline) 19 counter = 1 ' reset counter 20 21 ' exit Do Until...Loop statement 22 Do Until counter > 10 23 ' skip remaining code in loop only if counter = 5 24 If counter = 5 Then 25 Exit Do ' break out of loop 26 End If 27 28 Console.Write("{0} ", counter) ' output counter 29 counter += 1 ' increment counter 30 Loop 31 32 Console.WriteLine(vbNewLine & "Broke out of Do Until...Loop " & _ 33 " at counter = " & counter & vbnewline) 34 counter = 1 ' reset counter 35 36 ' exit While statement ExitTest.vb ( 2 of 3 ) Fig. 6.15 Exit statement in repetition statements. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.

Outline 52 37 While counter <= 10 38 ' skip remaining code in loop only if counter = 5 39 If counter = 5 Then 40 Exit While ' break out of loop 41 End If 42 43 Console.Write("{0} ", counter) ' output counter 44 counter += 1 ' increment counter 45 End While 46 47 Console.WriteLine( _ 48 vbnewline & "Broke out of While at counter = " & counter) 49 End Sub ' Main 50 End Module ' ExitTest ExitTest.vb ( 3 of 3 ) 1 2 3 4 Broke out of For...Next at counter = 5 1 2 3 4 Broke out of Do Until...Loop at counter = 5 1 2 3 4 Broke out of While at counter = 5 Fig. 6.15 Exit statement in repetition statements. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.

6.9 Using Continue in Repetition Statements 53 The Continue statement skips to the next iteration of the loop. The Continue Do statement can be executed in any Do statement. Continue For and Continue While are used in For... Next and While loops. Continue For increments the control variable by the Step value.

Figure 6.16 demonstrates the Continue statements. Outline 54 1 ' Fig. 6.16: ContinueTest.vb 2 ' Using the Continue statement in repetition statements. 3 Module ContinueTest 4 Sub Main() 5 Dim counter As Integer ' loop counter 6 7 ' skipping an iteration of a For...Next statement 8 For counter = 1 To 10 9 If counter = 5 Then 10 Continue For ' skip to next iteration of loop if counter = 5 11 End If 12 13 Console.Write("{0} ", counter) ' output counter 14 Next 15 16 Console.WriteLine(vbNewLine & _ 17 "Skipped printing in For...Next at counter = 5" & vbnewline) 18 counter = 0 ' reset counter 19 ContinueTest.vb ( 1 of 3 ) Fig. 6.16 Continue statement in repetition statements. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved.

Outline 55 20 ' skipping an iteration of a Do Until...Loop statement 21 Do Until counter >= 10 22 counter += 1 ' increment counter 23 24 If counter = 5 Then 25 Continue Do ' skip to next iteration of loop if counter = 5 26 End If 27 28 Console.Write("{0} ", counter) ' output counter 29 Loop 30 31 Console.WriteLine(vbNewLine & _ 32 "Skipped printing in Do Until...Loop at counter = 5" & vbnewline) 33 counter = 0 ' reset counter 34 35 ' skipping an iteration of a While statement 36 While counter < 10 37 counter += 1 ' increment counter 38 39 If counter = 5 Then 40 Continue While ' skip to next iteration of loop if counter = 5 41 End If ContinueTest.vb ( 2 of 3 ) Fig. 6.16 Continue statement in repetition statements. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved.

Outline 56 42 43 Console.Write("{0} ", counter) ' output counter 44 End While 45 46 Console.WriteLine( _ 47 vbnewline & "Skipped printing in While at counter = 5") 48 End Sub ' Main 49 End Module ' ContinueTest ContinueTest.vb ( 3 of 3 ) 1 2 3 4 6 7 8 9 10 Skipped printing in For...Next at counter = 5 1 2 3 4 6 7 8 9 10 Skipped printing in Do Until...Loop at counter = 5 1 2 3 4 6 7 8 9 10 Skipped printing in While at counter = 5 Fig. 6.16 Continue statement in repetition statements. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved.

57 6.10 Logical Operators The logical And operator can be used as follows: If gender = "F" And age >= 65 Then seniorfemales += 1 End If The If Then statement considers the combined condition: gender = "F" And age >= 65 Figure 6.17 is a truth table for the And operator. expression1 expression2 expression1 And expression2 False False False False True False True False False True True True Fig. 6.17 Truth table for the logical And operator.

58 6.10 Logical Operators (Cont.) Logical Or Operator The Or operator is used in the following segment: If (semesteraverage >= 90 Or finalexam >= 90) Then Console.WriteLine("Student grade is A") End If Figure 6.18 provides a truth table for the Or operator. expression1 expression2 expression1 Or expression2 False False False False True True True False True True True True Fig. 6.18 Truth table for the logical Or operator.

6.10 Logical Operators (Cont.) 59 Logical AndAlso and OrElse Operators AndAlso and OrElse are similar to the And and Or operators. (gender = "F" AndAlso age >= 65) The preceding expression stops evaluation immediately if gender is not equal to "F"; this is called short-circuit evaluation. Performance Tip 6.2 In expressions using operator AndAlso, if the separate conditions are independent of one an-other, place the condition most likely to be false as the leftmost condition. In expres-sions using operator OrElse, make the condition most likely to be true the leftmost condition. Each of these suggestions can reduce a program s execution time.

6.10 Logical Operators (Cont.) 60 AndAlso and OrElse operators can be used in place of And and Or. An exception to this rule occurs when the right operand of a condition produces a side effect: Console.WriteLine("How old are you?") If (gender = "F" And Console.ReadLine() >= 65) Then Console.WriteLine("You are a female senior citizen.") End If Error-Prevention Tip 6.8 Avoid expressions with side effects in conditions, because side effects often cause subtle errors.

61 6.10 Logical Operators (Cont.) Logical Xor Operator A condition i containing i the logical lexclusive OR( (Xor) operator is true if and only if one of its operands results in a true value and the other results in a false value. Figure 6.19 presents a truth table for the Xor operator. expression1 expression2 expression1 Xor expression2 False False False False True True True False True True True False Fig. 6.19 Truth table for the logical exclusive OR (Xor) operator.

62 6.10 Logical Operators (Cont.) Logical Not Operator The Not operator enables you to reverse the meaning of a condition. The logical l negation operator is a unary operator, requiring only one operand. If Not (grade = sentinelvalue) Then Console.WriteLine("The next grade is " & grade) End If The parentheses are necessary because Not has a higher precedence than the equality operator.

63 6.10 Logical Operators (Cont.) You can avoid using Not by expressing the condition differently: If grade <> sentinelvalue Then Console.WriteLine("The next grade is " & grade) End If Figure 6.20 provides a truth table for Not. expression False True Not expression True False Fig. 6.20 Truth table for operator Not (logical negation).

Figure 6.21 demonstrates the logical operators by displaying their truth tables. Outline 64 1 ' Fig. 6.21: LogicalOperators.vb 2 ' Using logical operators. 3 Module LogicalOperators 4 Sub Main() 5 ' display truth table for And 6 Console.WriteLine("And" & vbnewline & _ 7 "False And False: " & (False And False) & vbnewline & _ 8 "False And True: " & (False And True) & vbnewline & _ 9 "True And False: " & (True And False) & vbnewline & _ 10 "True And True: " & (True And True) & vbnewline) 11 12 ' display truth table for Or 13 Console.WriteLine("Or" i " & vbnewline & _ 14 "False Or False: " & (False Or False) & vbnewline & _ 15 "False Or True: " & (False Or True) & vbnewline & _ 16 "True Or False: " & (True Or False) & vbnewline & _ 17 "True Or True: " & (True Or True) & vbnewline) 18 LogicalOperators.vb (1of4) Fig. 6.21 Logical operator truth tables. (Part 1 of 4.) 2009 Pearson Education, Inc. All rights reserved.

Outline 65 19 ' display truth table for AndAlso 20 Console.WriteLine("AndAlso" & vbnewline & _ 21 "False AndAlso False: " & (False AndAlso False) & vbnewline & _ 22 "False AndAlso True: " & (False AndAlso True) & vbnewline & _ 23 "True AndAlso False: " & (True AndAlso False) & vbnewline & _ 24 "True AndAlso True: " & (True AndAlso True) & vbnewline) 25 26 ' display truth table for OrElse 27 Console.WriteLine("OrElse" & vbnewline & _ 28 "False OrElse False: " & (False OrElse False) & vbnewline & _ 29 "False OrElse True: " & (False OrElse True) & vbnewline & _ 30 "True OrElse False: " & (True OrElse False) & vbnewline & _ 31 "True OrElse True: " & (True OrElse True) & vbnewline) 32 33 ' display truth table for Xor 34 Console.WriteLine("Xor" & vbnewline & _ 35 "False Xor False: " & (False Xor False) & vbnewline & _ 36 "False Xor True: " & (False Xor True) & vbnewline & _ 37 "True Xor False: " & (True Xor False) & vbnewline & _ 38 "True Xor True: " & (True Xor True) & vbnewline) LogicalOperators.vb (2of4) Fig. 6.21 Logical operator truth tables. (Part 2 of 4.) 2009 Pearson Education, Inc. All rights reserved.

Outline 66 39 40 ' display truth table for Not 41 Console.WriteLine("Not" & vbnewline & "Not False: " & _ 42 (Not False) & vbnewline & "Not True: " & (Not True) & vbnewline) 43 End Sub ' Main 44 End Module ' LogicalOperators LogicalOperators.vb (3of4) And False And False: False False And True: False True And False: False True And True: True Or False Or False: False False Or True: True True Or False: True True Or True: True AndAlso False AndAlso False: False False AndAlso True: False True AndAlso False: False True AndAlso True: True (continued on next page...) Fig. 6.21 Logical operator truth tables. (Part 3 of 4.) 2009 Pearson Education, Inc. All rights reserved.

Outline 67 And False And False: False False And True: False True And False: False True And True: True Or False Or False: False False Or True: True True Or False: True True Or True: True AndAlso False AndAlso False: False False AndAlso True: False True AndAlso False: False True AndAlso True: True (continued from previous page ) LogicalOperators.vb (4of4) 4 Fig. 6.21 Logical operator truth tables. (Part 4 of 4.) 2009 Pearson Education, Inc. All rights reserved.

6.10 Logical Operators (Cont.) 68 Figure 6.22 displays the operators in decreasing order of precedence. Operators Type ^ exponentiation + - unary plus and minus * / multiplicative operators \ integer division Mod modulus + - additive operators Fig. 6.22 Precedence of the operators discussed so far. (Part 1 of 2.)

6.10 Logical Operators (Cont.) 69 Operators Type & concatenation < <= > >= = <> relational and equality Not And AndAlso Or OrElse Xor logical NOT logical AND logical inclusive OR logical exclusive OR = += -= *= /= \= ^= &= assignment Fig. 6.22 Precedence of the operators discussed so far. (Part 2 of 2.)

6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System Each object in a system goes through h a series of discrete states. State machine diagrams model key states of an object and show under what circumstances the object changes state. Figure 6.23 models some of the states of an ATM object. 70 Fig. 6.23 State machine diagram for some of the states of the ATM object.

6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System (Cont.) An activity diagram models an object s workflow. The activity diagram in Fig. 6.24 models the actions involved in executing a BalanceInquiry transaction. 71 Fig. 6.24 Activity diagram for a BalanceInquiry transaction.

6.11 Software Engineering Case Study: Identifying Objects States and Activities in the ATM System (Cont.) 72 Figure 6.25 shows a more complex activity diagram for a Withdrawal. Fig. 6.25 Activity diagram for a Withdrawal transaction.