104
2009 Pearson Education, Inc. All rights reserved. 1 5 Control Statements: Part 1

Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

1

5Control

Statements: Part 1

Page 2: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

2

Let’s all move one place on.– Lewis Carroll

The wheel is come full circle.– William Shakespeare, King Lear

How many apples fell onNewton’s head before he took the hint?

– Robert Frost

All the evolution we know ofproceeds from the vague to the definite.

– Charles Sanders Pierce

Page 3: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

3

OBJECTIVESIn this chapter you will learn: Basic problem-solving techniques. To develop algorithms through the process of

top-down, stepwise refinement. To use the If…Then and If…Then Else

selection statements to choose among alternative actions. To use the While, Do While…Loop and DoUntil...Loop repetition statements to execute statements in a program repeatedly.

Page 4: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

4

OBJECTIVES To use the compound assignment operators

to abbreviate assignment operations. To use counter-controlled repetition and

sentinel-controlled repetition. To use nested control statements. To add Visual Basic code to a Windows Forms

application.

Page 5: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

5

5.1 Introduction5.2 Algorithms5.3 Pseudocode5.4 Control Structures5.5 If…Then Selection Statement5.6 If …Then…Else Selection Statement5.7 While Repetition Statement5.8 Do While…Loop Repetition Statement5.9 Do Until…Loop Repetition Statement

Page 6: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

6

5.10 Compound Assignment Operators5.11 Formulating Algorithms: Counter-Controlled

Repetition5.12 Formulating Algorithms: Sentinel-Controlled

Repetition5.13 Formulating Algorithms: Nested Control

Statements 5.14 Formulating Algorithms: Nested Repetition

Statements5.15 Visual Basic Programming in a Windows

Forms Application5.16 (Optional) Software Engineering Case Study:

Identifying Class Attributes in the ATM System

Page 7: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

7

5.2 Algorithms

• Computers solve problems by executing a series of actions in a specific order.

• An algorithm is a procedure for solving a problem,in terms of:

– the actions to be executed and– the order in which these actions are executed

Page 8: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

8

5.2 Algorithms (Cont.)

• Consider the “rise-and-shine algorithm” followed by one junior executive for getting out of bed and going to work:

• (1) get out of bed, (2) take off pajamas, (3) take a shower, (4) get dressed, (5) eat breakfast and (6) carpool to work.

Page 9: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

9

5.2 Algorithms (Cont.)

• In a slightly different order:• (1) get out of bed, (2) take off pajamas, (3) get dressed,

(4) take a shower, (5) eat breakfast, (6) carpool to work.

• In this case, our junior executive shows up for work soaking wet.

• The order in which statements execute in a program is called program control.

Page 10: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

10

• Pseudocode helps programmers develop algorithms.– It is similar to every-day English; it is convenient and user-

friendly.– Pseudocode programs are not executed on computers.

• Pseudocode typically does not include variable declarations such as:

Dim number As Integer

5.3 Pseudocode

Software Engineering Observation 5.1Pseudocode helps you conceptualize a program during the program-design process. The pseudocode program can be converted to Visual Basic at a later point.

Page 11: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

11

• In sequential execution, statements are executedone after another.

• A transfer of control occurs when an executed statement does not directly follow the previously executed statement in the program.

• Early programs relied on GoTo statements, which were unstructured.

• Structured programming reduced development times with a clearer and easier format.

5.4 Control Structures

Page 12: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

12

• A UML activity diagram models the workflow of a software system.

• Activity diagrams are composed of symbols:– the action state symbol (a rectangle with rounded sides)– the diamond symbol– the small circle symbol– transition arrows, representing the flow

5.4 Control Structures (Cont.)

Page 13: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

13

• The sequence-structure activity diagram in Fig. 5.1 contains two action states.

• The solid circle symbols represent the activity’s initial- state and final state.

• Notes are similar to comments

5.4 Control Structures (Cont.)

Fig. 5.1 | Sequence-structure activity diagram.

Page 14: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

14

• Visual Basic provides three types of selection statements.

– The If…Then single-selection statement either performs an action or skips the action depending on a condition.

– The If…Then…Else double-selection statement performs an action if a condition is true, and performs a different action if the condition is false.

– The Select…Case double-selection statement performs one of many different actions, depending on the value of an expression.

5.4 Control Structures (Cont.)

Page 15: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

15

5.4 Control Structures (Cont.)

Software Engineering Observation 5.2Any Visual Basic program can be constructed from only 11 different types of control statements (sequence, three types of selection statements and seven types of repetition statements) combined in only two ways (control-statement stacking and control-statement nesting).

Page 16: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

16

If student’s grade is greater than or equal to 60 thenPrint “Passed”

• The preceding pseudocode If statement may be written in Visual Basic as:If studentGrade >= 60 Then

Console.WriteLine("Passed")End If

• The statement also could be written as:If studentGrade >= 60 Then Console.WriteLine("Passed")

5.5 If…Then Selection Statement

Page 17: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

17

• Logic errors result from unexpected occurrences inthe application or problems in the code (such ascalling the wrong method).

– A fatal logic error causes a program to fail and terminate prematurely.

– A nonfatal logic error causes the program to produce incorrect results.

5.5 If…Then Selection Statement (Cont.)

Page 18: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

18

• Figure 5.2 illustrates the single-selection If…Then statement.

– At the diamond decision symbol, the workflow continues along thepath determined by the guard conditions.

– Guard conditions are specified in the square brackets.

Fig. 5.2 | If...Then single-selection statement activity diagram.

5.5 If…Then Selection Statement (Cont.)

Page 19: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

19

If student’s grade is greater than or equal to 60 thenPrint “Passed”

ElsePrint “Failed”

• The preceding pseudocode If…Else statement may be written in Visual Basic as

If studentGrade >= 60 Then

Console.WriteLine("Passed")

ElseConsole.WriteLine("Failed")

End If

5.6 If…Then…Else Selection Statement

Page 20: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

20

Good Programming Practice 5.1Visual Basic indents both body statements of an If…Then…Else statement to improve readability.You should also follow this convention when programming in other languages.

Good Programming Practice 5.2A standard indentation convention should be applied consistently throughout your programs. It is difficultto read programs that do not use uniform spacing conventions.

5.6 If…Then…Else Selection Statement(Cont.)

Page 21: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

21

• An If…Then…Else statement can also be written using a conditional If expression:

Console.WriteLine(If(studentGrade >= 60, "Passed", "Failed"))

• A conditional If expression includes:– the condition– the value to return if the condition is true– the value to return if the condition is false

5.6 If…Then…Else Selection Statement(Cont.)

Page 22: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

22

• Figure 5.3 illustrates the flow of control in theIf…Then…Else statement.

5.6 If…Then…Else Selection Statement(Cont.)

Fig. 5.3 | If…Then…Else double-selection statement activity diagram.

Page 23: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

23

Nested If ...Then...Else Statements• Nested If…Then…Else statements test for multiple conditions:If student’s grade is greater than or equal to 90 then

Print “A”Else

If student’s grade is greater than or equal to 80 thenPrint “B”

Else If student’s grade is greater than or equal to 70 then

Print “C”Else

If student’s grade is greater than or equal to 60 thenPrint “D”

ElsePrint “F”

5.6 If…Then…Else Selection Statement(Cont.)

Page 24: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

24

• The preceding pseudocode may be written in Visual Basic asIf studentGrade >= 90 Then

Console.WriteLine("A")

ElseIf studentGrade >= 80 Then

Console.WriteLine("B")Else

If studentGrade >= 70 ThenConsole.WriteLine("C")

ElseIf studentGrade >= 60 Then

Console.WriteLine("D")Else

Console.WriteLine("F")End If

End IfEnd If

End If

5.6 If…Then…Else Selection Statement(Cont.)

Page 25: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

25

Good Programming Practice 5.3If there are several levels of indentation, each level should be indented additionally by the same amountof space; this gives programs a neatly structured appearance.

5.6 If…Then…Else Selection Statement(Cont.)

Page 26: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

26

• Most Visual Basic programmers prefer to use the ElseIf keyword:

If grade >= 90 ThenConsole.WriteLine("A")

ElseIf grade >= 80 ThenConsole.WriteLine("B")

ElseIf grade >= 70 ThenConsole.WriteLine("C")

ElseIf grade >= 60 ThenConsole.WriteLine("D")

ElseConsole.WriteLine("F")

End If

5.6 If…Then…Else Selection Statement(Cont.)

Page 27: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

27

• A repetition statement repeats an action, depending on the loop-continuation condition.

While there are more items on my shopping listPut next item in cartCross it off my list

• When the condition becomes false, the first statement after the repetition statement executes.

5.7 While Repetition Statement

Page 28: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

28

1 ' Fig. 5.4: PowersOfThree.vb

2 ' Demonstration of While statement.

3 Module PowersOfThree

4 Sub Main()

5 Dim product As Integer = 3

6 7 ' statement multiplies and displays product

8 ' while product is less than or equal to 100

9 While product <= 100

10 Console.Write(product & " ") 11 product = product * 3 ' compute next power of 3 12 End While 13

Outline

PowersOfThree.vb

(1 of 2 )

• Consider a program designed to find the firstpower of 3 larger than 100 (Fig. 5.4).

product is initially set to 3.

product is multiplied by 3each iteration

Fig. 5.4 | While repetition statement used to print powers of 3. (Part 1 of 2.)

Page 29: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

29

14 Console.WriteLine() ' write blank line 15 16 ' print result 17 Console.WriteLine("First power of 3 " & _ 18 "larger than 100 is " & product) 19 End Sub ' Main 20 End Module ' PowersOfThree

3 9 27 81

First power of 3 larger than 100 is 243

Outline

PowersOfThree.vb

(2 of 2 )

Fig. 5.4 | While repetition statement used to print powers of 3. (Part 2 of 2.)

Page 30: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

30

• The UML activity diagram (Fig. 5.5) illustrates the flowof control in a While statement.

• The diamond merge symbol joins two flows of activityinto one.

5.7 While Repetition Statement (Cont.)

Fig. 5.5 | While repetition statement activity diagram.

Page 31: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

31

5.7 While Repetition Statement (Cont.)

Common Programming Error 5.1Failure to provide the body of a While statement with an action that eventually causes the loop-continuation con-dition to become false is a logic error. Such a repetition statement never terminates, resulting in a logic error called an “infinite loop.”

Page 32: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

32

1 ' Fig. 5.6: DoWhile.vb

2 ' Demonstration of the Do While...Loop statement.

3 Module DoWhile

4 Sub Main()

5 Dim product As Integer = 3 ' initialize product

6 7 ' statement multiplies and displays the

8 ' product while it is less than or equal to 100

9 Do While product <= 100

10 Console.Write(product & " ") 11 product = product * 3 12 Loop

Outline

DoWhile.vb

(1 of 2 )

• The Do While…Loop repetition statementbehaves exactly like the While repetitionstatement (Fig. 5.6).

product is initially set to 3.

product is multiplied by 3each iteration

Fig. 5.6 | Do While…Loop repetition statement demonstration. (Part 1 of 2.)

Page 33: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

33

13 14 Console.WriteLine() ' write blank line 15 16 ' print result 17 Console.WriteLine("First power of 3 " & _ 18 "larger than 100 is " & product) 19 End Sub ' Main 20 End Module ' DoWhile

3 9 27 81

First power of 3 larger than 100 is 243

Outline

DoWhile.vb

(2 of 2 )

Fig. 5.6 | Do While…Loop repetition statement demonstration. (Part 2 of 2.)

Page 34: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

34

5.8 Do While…Loop Repetition Statement(Cont.)

Common Programming Error 5.2Failure to provide the body of a Do While…Loopstatement with an action that eventually causes theloop-continuation condition to become false creates an infinite loop.

Page 35: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

35

1 ' Fig. 5.7: DoUntil.vb

2 ' Demonstration of the Do Until...Loop statement.

3 Module DoUntil

4 Sub Main()

5 Dim product As Integer = 3

6 7 ' find first power of 3 larger than 100

8 Do Until product > 100

9 Console.Write(product & " ")

10 product = product * 3 11 Loop

Outline

DoUntil.vb

(1 of 2 )

• A Do Until…Loop is executed repeatedly as longas the loop-termination condition is false (Fig. 5.7).

Fig. 5.7 | Do Until…Loop repetition statement demonstration. (Part 1 of 2.)

Page 36: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

36

12 13 Console.WriteLine() ' write blank line 14 15 ' print result 16 Console.WriteLine("First power of 3 " & _ 17 "larger than 100 is " & product) 18 End Sub ' Main 19 End Module ' DoUntil

3 9 27 81

First power of 3 larger than 100 is 243

Outline

Common Programming Error 5.3Failure to provide the body of a Do Until…Loop statementwith an action that eventually causes the loop-termination condition to become true creates an infinite loop.

DoUntil.vb

(2 of 2 )

Fig. 5.7 | Do Until…Loop repetition statement demonstration. (Part 2 of 2.)

Page 37: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

37

5.10 Compound Assignment Operators

Fig. 5.8 | Compound assignment operators.

Compound assignment operator

Sample expression Explanation Assigns

Assume: c = 4, d = "He"

+= c += 7 c = c + 7 11 to c

-= c -= 3 c = c - 3 1 to c

*= c *= 4 c = c * 4 16 to c

/= c /= 2 c = c / 2 2 to c

\= c \= 3 c = c \ 3 1 to c

^= c ^= 2 c = c ^ 2 16 to c

&= d &= "llo" d = d & "llo" "Hello" to d

Page 38: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

38

1 ' Fig. 5.9: Assignment.vb

2 ' Using a compound assignment operator to calculate a power of 2.

3 Module Assignment

4 Sub Main()

5 Dim exponent As Integer ' power input by user

6 Dim result As Integer = 2 ' number to raise to a power

7 8 ' prompt user for exponent

9 Console.Write("Enter an integer exponent: ")

10 exponent = Console.ReadLine() ' input exponent

Outline

Assignment.vb

(1 of 2 )

• Figure 5.9 calculates a power of two using theexponentiation assignment operator.

Fig. 5.9 | Exponentiation using a compound assignment operator. (Part 1 of 2.)

Page 39: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

39

11 12 result ^= exponent ' same as result = result ^ exponent 13 Console.WriteLine("result ^= exponent: " & result) 14 15 result = 2 ' reset result to 2 16 result = result ^ exponent ' same as result ^= exponent 17 Console.WriteLine("result = result ^ exponent: " & result) 18 End Sub ' Main 19 End Module ' Assignment

Enter an integer exponent: 8 result ^= exponent: 256

result = result ^ exponent: 256

Outline

Assignment.vb

(2 of 2 )

Fig. 5.9 | Exponentiation using a compound assignment operator. (Part 2 of 2.)

Page 40: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

40

• Consider the following problem statement:A class of 10 students took a quiz. The grades for this quiz are made available to you. Determine the class average on the quiz.

• The algorithm for solving this problem on a computer must input each grade, keep track of the total of all grades input, perform the averaging calculation and print the result.

5.11 Formulating Algorithms: Counter-Controlled Repetition

Page 41: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

41

5.11 Formulating Algorithms: Counter-Controlled Repetition (Cont.)

Pseudocode Algorithm with Counter-Controlled Repetition• Counter-controlled repetition (Fig. 5.10) inputs and

processes the grades one at a time.

1 Set total to zero

2 Set grade counter to one

3 4 While grade counter is less than or equal to ten

5 Prompt the user to enter the next grade

6 Input the next grade

7 Add the grade into the total

8 Add one to the grade counter

9 10 Set the class average to the total divided by ten 11 Print the class average

Fig. 5.10 | Pseudocode algorithm that uses counter-controlled repetition to

solve the class-average problem.

Page 42: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

42

1 ' Fig. 5.11: GradeBook.vb

2 ' GradeBook class that solves class-average problem using

3 ' counter-controlled repetition.

4 Public Class GradeBook

5 Private courseNameValue As String ' course name for this GradeBook

6 7 ' constructor initializes CourseName with String supplied as argument

8 Public Sub New(ByVal name As String)

9 CourseName = name ' validate and store course name

10 End Sub ' New 11 12 ' property that gets and sets the course name; the Set accessor 13 ' ensures that the course name has at most 25 characters 14 Public Property CourseName() As String 15 Get ' retrieve courseNameValue 16 Return courseNameValue 17 End Get

Outline

GradeBook.vb

(1 of 4 )

• The pseudocode is now converted to Visual Basic (Fig. 5.11).

Fig. 5.11 | Counter-controlled repetition: Class-average problem. (Part 1 of 4.)

Page 43: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

43

18 19 Set(ByVal value As String) ' set courseNameValue 20 If value.Length <= 25 Then ' if value has 25 or fewer characters 21 courseNameValue = value ' store the course name in the object 22 Else ' if name has more than 25 characters 23 ' set courseNameValue to first 25 characters of parameter name 24 ' start at 0, length of 25 25 courseNameValue = value.Substring(0, 25) 26 27 Console.WriteLine( _ 28 "Course name (" & value & ") exceeds maximum length (25).") 29 Console.WriteLine( _ 30 "Limiting course name to first 25 characters." & vbCrLf) 31 End If 32 End Set 33 End Property ' CourseName 34

Outline

GradeBook.vb

(2 of 4 )

Fig. 5.11 | Counter-controlled repetition: Class-average problem. (Part 2 of 4.)

Page 44: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

44

35 ' display a welcome message to the GradeBook user 36 Public Sub DisplayMessage() 37 ' this statement uses property CourseName to get the 38 ' name of the course this GradeBook represents 39 Console.WriteLine("Welcome to the grade book for " _ 40 & vbCrLf & CourseName & "!" & vbCrLf) 41 End Sub ' DisplayMessage 42 43 ' determine class average based on 10 grades entered by user 44 Public Sub DetermineClassAverage() 45 Dim total As Integer ' sum of grades entered by user 46 Dim gradeCounter As Integer ' number of grades input 47 Dim grade As Integer ' grade input by user 48 Dim average As Integer ' average of grades 49 50 ' initialization phase 51 total = 0 ' set total to zero 52 gradeCounter = 1 ' prepare to loop 53

Outline

GradeBook.vb

(3 of 4 )

Counter initialized before the repetition statement.

Fig. 5.11 | Counter-controlled repetition: Class-average problem. (Part 3 of 4.)

Page 45: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

45

54 ' processing phase 55 While gradeCounter <= 10 ' loop 10 times 56 ' prompt for and input grade from user 57 Console.Write("Enter grade: ") ' prompt for grade 58 grade = Console.ReadLine() ' input the next grade 59 total += grade ' add grade to total 60 gradeCounter += 1 ' add 1 to gradeCounter 61 End While 62 63 ' termination phase 64 average = total \ 10 ' integer division yields integer result 65 66 ' display total and average of grades 67 Console.WriteLine(vbCrLf & "Total of all 10 grades is " & total) 68 Console.WriteLine("Class average is " & average) 69 End Sub ' DetermineClassAverage 70 End Class ' GradeBook

Outline

GradeBook.vb

(4 of 4 )

The counter specifies the number of times the statements will execute.

Fig. 5.11 | Counter-controlled repetition: Class-average problem. (Part 4 of 4.)

Page 46: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

46

Good Programming Practice 5.4Although Visual Basic initializes numeric variablesto 0, it is a good practice to initialize certain variables explicitly to avoid confusion and improve program readability.

Good Programming Practice 5.5Separating declara-tions from other statementswith a blank line improves readability.

5.11 Formulating Algorithms: Counter-Controlled Repetition (Cont.)

Page 47: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

47

Software Engineering Observation 5.3The most difficult part of solving a problem on a computer is developing the algorithm for the solution. Once a correct algorithm has been specified, the process of producing a working Visual Basic program from the algorithm is normally straightforward.

5.11 Formulating Algorithms: Counter-Controlled Repetition (Cont.)

Page 48: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

48

1 ' Fig. 5.12: GradeBookTest.vb

2 ' Create GradeBook object and invoke its DetermineClassAverage method.

3 Module GradeBookTest

4 Sub Main()

5 ' create GradeBook object gradeBook and

6 ' pass course name to constructor

7 Dim gradeBook As New GradeBook("CS101 Introduction to VB")

8 9 gradeBook.DisplayMessage() ' display welcome message

10 gradeBook.DetermineClassAverage() ' find average of 10 grades 11 End Sub ' Main 12 End Module ' GradeBookTest

Outline

GradeBookTest.vb

(1 of 2 )

• Module GradeBookTest (Fig. 5.12) creates an object of class GradeBook and demonstrates its capabilities.

Fig. 5.12 | Module GradeBookTest creates an object of class GradeBookand invokes its DetermineClassAverage method. (Part 1 of 2.)

Page 49: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

49

Welcome to the grade book for

CS101 Introduction to VB!

Enter grade: 65 Enter grade: 78 Enter grade: 89 Enter grade: 67 Enter grade: 87 Enter grade: 98 Enter grade: 93 Enter grade: 85 Enter grade: 82 Enter grade: 100

Total of all 10 grades is 844

Class average is 84

Outline

Common Programming Error 5.4Assuming that integer division rounds (rather than truncates)can lead to incorrect results. For example, 7 divided by 4, whichyields 1.75 in conventional arithmetic, truncates to 1 in integerarithmetic, rather than rounding to 2.

GradeBookTest.vb

(2 of 2 )

Fig. 5.12 | Module GradeBookTest creates an object of class GradeBookand invokes its DetermineClassAverage method. (Part 2 of 2.)

Page 50: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

50

5.12 Formulating Algorithms: Sentinel-Controlled Repetition

• Consider the following problem:Develop a class-averaging program that processes grades for an arbitrary number of students each time it is run.• A sentinel value can be used to indicate when no more

grades will be entered.• Sentinel-controlled repetition is called indefinite

repetition because the number of repetitions is notknown before the loop begins its execution.

Common Programming Error 5.5Choosing a sentinel value that is also a legitimate data valuecould result in a logic error that would cause a program toproduce incorrect results.

Page 51: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

51

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

• Approach the class-average program with top-down, stepwise refinement.

• Begin with a single statement that conveys the overall function of the program:

Determine the class average for the quiz• Divide into a series of smaller tasks that are listed in the

order in which they must be performed:Initialize variablesInput, sum and count the quiz gradesCalculate and print the class average

Page 52: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

52

5.12 Formulating Algorithms: Sentinel-Controlled Repetition

Software Engineering Observation 5.4Each refinement, including the top, is a complete specification of the algorithm; only the level of detailin each refinement varies.

Software Engineering Observation 5.5Many algorithms can be divided logically into threephases—an initialization phase that initializes the program variables, a processing phase that inputs data values and adjusts program variables accordingly, and a termination phase that calculates and prints the results.

Page 53: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

53

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

• In the second refinement, we commit to specific variables:Initialize total to zeroInitialize grade counter to zero• The algorithm requires a repetition statement that inputs and

processes each grade:Prompt the user to enter the first grade

Input the first grade (possibly the sentinel)While the user has not yet entered the sentinel

Add this grade into the running totalAdd one to the grade counterPrompt the user to enter the next gradeInput the next grade (possibly the sentinel)

Page 54: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

54

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Calculate and print the class average• The preceding pseudocode statement can be refined as

follows:If the grade counter is not equal to zero then

Set the average to the total divided by the counterPrint the class average

ElsePrint “No grades were entered”

• An If statement is used to avoid division by zero.

Page 55: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

55

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

• The complete second refinement is shown in Fig. 5.13.

Fig. 5.13 | Class-average problem pseudocode algorithm withsentinel-controlled repetition.

1 Initialize total to zero

2 Initialize grade counter to zero

3 4 Prompt the user to enter the first grade

5 Input the first grade (possibly the sentinel)

6 7 While the user has not yet entered the sentinel

8 Add this grade into the running total

9 Add one to the grade counter

10 Prompt the user to enter the next grade

11 Input the next grade (possibly the sentinel)

12 13 If the grade counter is not equal to zero then 14 Set the average to the total divided by the counter 15 Print the class average

16 Else 17 Print “No grades were entered”

Page 56: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

56

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Error-Prevention Tip 5.1When performing division by an expression whose value could be zero, explicitly test for this case and handle it appropriately in your program. Such handling could be as simple as printing an error message.

Good Programming Practice 5.6Include blank lines in pseudocode algorithms to improve readability. The blank lines separate pseudocode controlstatements and the algorithms’ phases.

Software Engineering Observation 5.6You terminate the top-down, stepwise refinement processwhen the pseudocode algorithm is specified in sufficient detailfor the pseudocode to be converted to a Visual Basic program.

Page 57: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

57

1 ' Fig. 5.14: GradeBook.vb

2 ' GradeBook class that solves class-average problem using

3 ' sentinel-controlled repetition.

4 Public Class GradeBook

5 Private courseNameValue As String ' course name for this GradeBook

6 7 ' constructor initializes CourseName with String supplied as argument

8 Public Sub New(ByVal name As String)

9 CourseName = name ' validate and store course name

10 End Sub ' New 11 12 ' property that gets and sets the course name; the Set accessor 13 ' ensures that the course name has at most 25 characters 14 Public Property CourseName() As String 15 Get ' retrieve courseNameValue 16 Return courseNameValue 17 End Get

Outline

GradeBook.vb

(1 of 5 )

• Class GradeBook (Fig. 5.14) contains the method Determine­ClassAverage, which implements the algorithm.

Fig. 5.14 | Sentinel-controlled repetition: Class-average problem. (Part 1 of 5.)

Page 58: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

58

18 19 Set(ByVal value As String) ' set courseNameValue 20 If value.Length <= 25 Then ' if value has 25 or fewer characters 21 courseNameValue = value ' store the course name in the object 22 Else ' if name has more than 25 characters 23 ' set courseNameValue to first 25 characters of parameter name 24 ' start at 0, length of 25 25 courseNameValue = value.Substring(0, 25) 26 27 Console.WriteLine( _ 28 "Course name (" & value & ") exceeds maximum length (25).") 29 Console.WriteLine( _ 30 "Limiting course name to first 25 characters." & vbCrLf) 31 End If 32 End Set 33 End Property ' CourseName 34

Outline

GradeBook.vb

(2 of 5 )

Fig. 5.14 | Sentinel-controlled repetition: Class-average problem. (Part 2 of 5.)

Page 59: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

59

35 ' display a welcome message to the GradeBook user 36 Public Sub DisplayMessage() 37 ' this statement uses property CourseName to get the 38 ' name of the course this GradeBook represents 39 Console.WriteLine("Welcome to the grade book for " _ 40 & vbCrLf & CourseName & "!" & vbCrLf) 41 End Sub ' DisplayMessage 42 43 ' determine class average based on 10 grades entered by user 44 Public Sub DetermineClassAverage() 45 Dim total As Integer ' sum of grades entered by user 46 Dim gradeCounter As Integer ' number of grades input 47 Dim grade As Integer ' grade input by user 48 Dim average As Double ' average of all grades 49 50 ' initialization phase 51 total = 0 ' clear total 52 gradeCounter = 0 ' prepare to loop 53

Outline

GradeBook.vb

(3 of 5 )

Counter is initialized to 0

Fig. 5.14 | Sentinel-controlled repetition: Class-average problem. (Part 3 of 5.)

Page 60: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

60

54 ' processing phase 55 ' prompt for input and read grade from user 56 Console.Write("Enter grade or -1 to quit: ") 57 grade = Console.ReadLine() 58 59 ' sentinel-controlled loop where -1 is the sentinel value 60 While grade <> -1 61 total += grade ' add grade to total 62 gradeCounter += 1 ' add 1 to gradeCounter 63 64 ' prompt for and input next grade from user 65 Console.Write("Enter grade or -1 to quit: ") ' prompt 66 grade = Console.ReadLine() ' input next grade 67 End While 68

Outline

GradeBook.vb

(4 of 5 )

User is prompted for the first value

Repeats until sentinel value is entered

Fig. 5.14 | Sentinel-controlled repetition: Class-average problem. (Part 4 of 5.)

Page 61: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

61

69 ' termination phase 70 If gradeCounter <> 0 Then ' if user entered at least one grade 71 ' calculate average of all grades entered 72 average = total / gradeCounter 73 74 ' display total and average (with two digits of precision) 75 Console.WriteLine(vbCrLf & "Total of the " & gradeCounter & _ 76 " grades entered is " & total) 77 Console.WriteLine("Class average is {0:F}", average) 78 Else ' no grades were entered, so output appropriate message 79 Console.WriteLine("No grades were entered") 80 End If 81 End Sub ' DetermineClassAverage 82 End Class ' GradeBook

Outline

GradeBook.vb

(5 of 5 )

“{0:F}” indicates that the value should be displayed as a fixed-point number.

Fig. 5.14 | Sentinel-controlled repetition: Class-average problem. (Part 5 of 5.)

Page 62: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

62

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Good Programming Practice 5.7In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value.

Page 63: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

63

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Floating-Point Number Precision and Memory Requirements• Variables of type Single represent single-precision

floating-point numbers and have seven significant digits.• Variables of type Double represent double-precision

floating-point numbers.Floating-Point Numbers are Approximations• Due to the imprecise nature of floating-point numbers, type Double is preferred over type Single because Doublevariables can represent floating-point numbers more accurately.

Page 64: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

64

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Common Programming Error 5.6Using floating-point numbers in a manner that assumes they are represented precisely can lead to logic errors.

Page 65: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

65

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Implicitly Converting Between Primitive Types• The floating-point division operator operates on

Single, Double and Decimal values.– To ensure that the operands are one of these types, Visual Basic

performs implicit conversion.– If both operands are of type Integer, the operands will be

promoted to Double values.

Page 66: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

66

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

• “{0:F}” indicates that the value should be displayed as a fixed-point number.

• This is an example of formatted output of a value’s data.

• The numeric value that appears before the colon indicates which argument will be formatted.

• The value after the colon is known as a format specifier.

Page 67: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

67

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

• Some common format specifiers are summarized in Fig. 5.15.

Fig. 5.15 | Formatting codes for Strings.

Format Code Description

C Currency. Formats the currency based on the computer’s locale setting.

E Scientific notation. For example, 956.2 is formatted as 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 integer. 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. (Varies by locale.) X Hexadecimal integer. Displays the integer in hexadecimal (base-16)

notation.

Page 68: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

68

5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)

Good Programming Practice 5.8When formatting with two positions to the right of the decimal point, some programmers prefer to use the format specifier F2 for clarity.

Page 69: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

69

1 ' Fig. 5.16: GradeBookTest.vb

2 ' Create GradeBook object and invoke its DetermineClassAverage method.

3 Module GradeBookTest

4 Sub Main()

5 ' create GradeBook object gradeBook and

6 ' pass course name to constructor

7 Dim gradeBook As New GradeBook("CS101 Introduction to VB")

8 9 gradeBook.DisplayMessage() ' display welcome message

10 gradeBook.DetermineClassAverage() ' find average of grades 11 End Sub ' Main 12 End Module ' GradeBookTest

Outline

GradeBookTest.vb

(1 of 2 )

• The three grades entered during the sample execution of module GradeBookTest(Fig. 5.16) total 257, which yields the rounded average 85.67.

Fig. 5.16 | GradeBookTest module creates an object of class GradeBook(Fig. 5.14) and invokes its DetermineClassAverage method. (Part 1 of 2.)

Page 70: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

70

Welcome to the grade book for

CS101 Introduction to VB!

Enter grade or -1 to quit: 97 Enter grade or -1 to quit: 88 Enter grade or -1 to quit: 72 Enter grade or -1 to quit: - 1

Total of the 3 grades entered is 257

Class average is 85.67

Outline

GradeBookTest.vb

(2 of 2 )

Fig. 5.16 | GradeBookTest module creates an object of class GradeBook(Fig. 5.14) and invokes its DetermineClassAverage method. (Part 2 of 2.)

Page 71: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

71

5.13 Formulating Algorithms: Nested Control Statements

• Consider the following problem statement:A college offers a course that prepares students for the statelicensing exam for real es-tate brokers. The college wants toknow how well its students did on the exam. You have beengiven a list of 10 students.

1. Tally each exam result (“P” or “F”).2. Display a summary of the exam results.3. If more than eight students passed the exam, print the message

“Raise tuition.”

Page 72: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

72

5.13 Formulating Algorithms: Nested Control Statements (Cont.)

• Proceed with top-down, stepwise refinement.Analyze exam results and decide if tuition should be raised

• Our first refinement isInitialize variablesInput the ten exam grades, and count passes and failuresPrint a summary of the exam results and decide if tuition should be raised• Only the counters for the number of passes, number of

failures and number of students need to be initialized.Initialize passes to zeroInitialize failures to zeroInitialize student to one

Page 73: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

73

5.13 Formulating Algorithms: Nested Control Statements (Cont.)

Input the 10 exam results, and count passes and failures• A loop successively inputs the result of each exam.While student is less than or equal to 10

Prompt the user to enter the next exam resultInput the next exam result

If the student passed thenAdd one to passes

ElseAdd one to failures

Add one to student

Page 74: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

74

5.13 Formulating Algorithms: Nested Control Statements (Cont.)

Print a summary of the exam results and decide if tuition should be raised• The preceding pseudocode statement may be refined

as follows:Print the number of passesPrint the number of failuresIf more than eight students passed then

Print “Raise tuition”

Page 75: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

75

5.13 Formulating Algorithms: Nested Control Statements (Cont.)

Complete Second Refinement of Pseudocode and Conversion to Class Analysis• The complete second refinement of the pseudocode

appears in Fig. 5.17.

Page 76: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

76

5.13 Formulating Algorithms: Nested Control Statements (Cont.)

Fig. 5.17 | Pseudocode for examination-results problem.

1 Initialize passes to zero

2 Initialize failures to zero

3 Initialize student to one

4 5 While student is less than or equal to 10

6 Prompt the user to enter the next exam result

7 Input the next exam result

8 9 If the student passed then

10 Add one to passes

11 Else

12 Add one to failures

13 14 Add one to student

15 16 Print the number of passes 17 Print the number of failures 18 19 If more than eight students passed then 20 Print “Raise tuition”

Page 77: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

77

1 ' Fig. 5.18: Analysis.vb

2 ' Analysis of examination results.

3 Public Class Analysis

4 ' input and analyze exam results

5 Public Sub ProcessExamResults()

6 ' initializing variables in declarations

7 Dim passes As Integer = 0 ' number of passes

8 Dim failures As Integer = 0 ' number of failures

9 Dim student As Integer = 1 ' student counter

10 Dim result As String ' one exam result (obtains value from user) 11 12 ' process 10 students using counter-controlled loop 13 While student <= 10 14 Console.Write("Enter result (P = pass, F = fail): ") 15 result = Console.ReadLine() 16

Outline

Analysis.vb

(1 of 2 )

• The pseudocode is now converted into Visual Basic (Fig. 5.18).

Fig. 5.18 | Nested control statements: Examination-results problem. (Part 1 of 2.)

Page 78: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

78

17 ' nested control statement 18 If result = "P" Then 19 passes += 1 ' increment number of passes 20 Else 21 failures += 1 ' increment number of failures 22 End If 23 24 student += 1 ' increment student counter 25 End While 26 27 ' display exam results 28 Console.WriteLine( _ 29 "Passed: " & passes & vbCrLf & "Failed: " & failures) 30 31 ' raise tuition if more than 8 students passed 32 If passes > 8 Then 33 Console.WriteLine("Raise tuition") 34 End If 35 End Sub ' ProcessExamResults 36 End Class ' Analysis

Outline

Analysis.vb

(2 of 2 )

Fig. 5.18 | Nested control statements: Examination-results problem. (Part 2 of 2.)

Page 79: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

79

1 ' Fig. 5.19: AnalysisTest.vb

2 ' Test program for class Analysis.

3 Module AnalysisTest

4 Sub Main()

5 Dim application As New Analysis() ' create Analysis object

6 application.ProcessExamResults() ' call method to process results

7 End Sub ' Main

8 End Module ' AnalysisTest

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): F

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

(continued on next page...)

Outline

AnalysisTest.vb

(1 of 2 )

• Module AnalysisTest (Fig. 5.19) tests an Analysis object.

Fig. 5.19 | Test program for class Analysis. (Part 1 of 2.)

Page 80: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

80

(continued from previous page…) Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Passed: 9

Failed: 1

Raise tuition

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): F

Enter result (P = pass, F = fail): F

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Enter result (P = pass, F = fail): P

Passed: 8

Failed: 2

Outline

AnalysisTest.vb

(2 of 2 )

Fig. 5.19 | Test program for class Analysis. (Part 2 of 2.)

Page 81: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

81

5.14 Formulating Algorithms: Nested Repetition Statements

• Consider the following problem statement:Write a console application that draws a filled square consisting solely of one type of character. The side of the square and the fill character should be entered by the user. The length of the side should not exceed 20 characters.

Page 82: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

82

5.14 Formulating Algorithms: Nested Repetition Statements (Cont.)

Evolving the PseudocodeDraw a square of fill characters• Our first refinement is

Prompt for the fill characterInput the fill characterPrompt for the side of the squareInput the side of the squareDraw the square if its side is less than or equal to 20; otherwise print an error message

Page 83: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

83

5.14 Formulating Algorithms: Nested Repetition Statements (Cont.)

Draw the square• This pseudocode statement can be implemented by

using one loop nested inside another.Set row to oneWhile row is less than or equal to side

Set column to oneWhile column is less than or equal to side

Print the fill characterIncrement column by one

Print a line feed/carriage returnIncrement row by one

Page 84: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

84

• The complete second refinement appears in Fig. 5.20.

Fig. 5.20 | Second refinement of the pseudocode.

1 Prompt for the fill character

2 Input the fill character

3 4 Prompt for the side of the square

5 Input the side of the square

6 7 If the side of the square is less than or equal to 20 then

8 Set row to one

9 10 While row is less than or equal to side

11 Set column to one

12 13 While column is less than or equal to side

14 Print the fill character

15 Increment column by one

16 17 Print a line feed/carriage return

18 Increment row by one

19 Else 20 Print “Side is too large”

5.14 Formulating Algorithms: Nested Repetition Statements (Cont.)

Page 85: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

85

Software Engineering Observation 5.77Many experienced programmers write programs without ever using program-development tools like pseudocode. They feel that their ultimate goal is to solve the problem on a computer and that writing pseudocode merely delays producing final outputs. Although this might work for simple and familiar problems, it can lead to serious errors and delaysin large, complex projects.

5.14 Formulating Algorithms: Nested Repetition Statements (Cont.)

Page 86: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

86

1 ' Fig. 5.21: Box.vb

2 ' Class can be used to draw a square of a specified length, using

3 ' a specified fill character.

4 Public Class Box

5 Private sideValue As Integer ' length of side of square

6 Private fillCharacterValue As String ' character used to draw square

7 8 ' property provides access to side length of box

9 Public Property Side() As Integer

10 Get 11 Return sideValue ' return side length 12 End Get 13 14 Set(ByVal value As Integer) 15 sideValue = value ' modify side length 16 End Set 17 End Property ' Side 18

Outline

Box.vb

(1 of 3 )

• The pseudocode is converted into Visual Basic (Fig. 5.21).

Fig. 5.21 | Nested repetition statements used to print a squareof symbols. (Part 1 of 3.)

Page 87: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

87

19 ' property provides access to fill character for drawing box 20 Public Property FillCharacter() As String 21 Get 22 Return fillCharacterValue ' return fill character 23 End Get 24 25 Set(ByVal value As String) 26 fillCharacterValue = value ' modify fill character 27 End Set 28 End Property ' FillCharacter 29 30 ' display box 31 Public Sub Display() 32 Dim row As Integer ' current row 33 Dim column As Integer ' current column 34 35 If Side <= 20 Then ' if true, then print the box 36 row = 1 37

Outline

Box.vb

(2 of 3 )

Fig. 5.21 | Nested repetition statements used to print a squareof symbols. (Part 2 of 3.)

Page 88: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

88

38 ' this While is nested inside the If in lines 35-55 39 While row <= Side ' controls row being printed 40 column = 1 ' prepare to print first character in the row 41 42 ' this loop prints one row of the square 43 ' and is nested inside the While in lines 39-52 44 While column <= Side 45 ' print fill character and a space 46 Console.Write(FillCharacter & " ") 47 column += 1 ' increment column 48 End While 49 50 Console.WriteLine() ' position cursor to next line 51 row += 1 ' increment row 52 End While 53 Else ' condition (Side <= 20) is false 54 Console.WriteLine("Side too large") 55 End If 56 End Sub ' Display 57 End Class ' Box

Outline

Box.vb

(3 of 3 )

Fig. 5.21 | Nested repetition statements used to print a squareof symbols. (Part 3 of 3.)

Page 89: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

89

1 ' Fig. 5.22: BoxTest.vb

2 ' Program draws square by creating an object of class Box.

3 Module BoxTest

4 ' Main begins program execution

5 Sub Main()

6 Dim box As New Box()

7 8 ' obtain fill character and side length from user

9 Console.Write("Enter fill character: ")

10 box.FillCharacter = Console.ReadLine() 11 Console.Write("Enter side length (must be 20 or less): ") 12 box.Side = Console.ReadLine() 13 14 box.Display() ' display box 15 End Sub ' Main 16 End Module ' BoxTest

Outline

BoxTest.vb

(1 of 2 )

• The BoxTest module (Fig. 5.22) uses the Boxclass.

Fig. 5.22 | Using class Box to draw a square. (Part 1 of 2.)

Page 90: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

90

Enter fill character: # Enter side length (must be 20 or less): 8 # # # # # # # #

# # # # # # # #

# # # # # # # #

# # # # # # # #

# # # # # # # #

# # # # # # # #

# # # # # # # #

# # # # # # # #

Enter fill character: * Enter side length (must be 20 or less): 5 * * * * *

* * * * *

* * * * *

* * * * *

* * * * *

Enter fill character: $ Enter side length (must be 20 or less): 37 Side too large

Outline

BoxTest.vb

(2 of 2 )

Fig. 5.22 | Using class Box to draw a square. (Part 2 of 2.)

Page 91: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

91

• Open the ASimpleProgram project (Fig. 5.23).• Change the name of the Label to welcomeLabel

and the name of the PictureBox to bugPictureBox.

Fig. 5.23 | IDE showing program code for ASimpleProgram.vb.

5.15 Visual Basic Programming in a Windows Forms Application

Page 92: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

92

• The IDE generates the Visual Basic code that defines how the GUI appears.

– Go into the Solution Explorer and click the Show AllFiles button ( ).

– Click the plus sign to the left of ASimpleProgramForm.vbto expand its node, and double click ASimpleProgramForm.Designer.vb.

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Page 93: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

93

• Keyword Inherits indicates that the class uses existing pieces from another class.

– Form is the base class and ASimpleProgramForm is the derived class.

• Form provides the capabilities your application needs to appear as a window.

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Fig. 5.24 | Windows Form Designer generated code.

Page 94: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

94

• When a control is placed on the Form, the IDE adds code to the designer file.

• This code (Fig. 5.25) specifies the property values for welcomeLabel.

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Property initializations forwelcomeLabel

Fig. 5.25 | Property initializations generated by the WindowsForm Designer for welcomeLabel.

Page 95: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

95

Modifying Properties in Design View• The values assigned to the properties are based on the

values in the Properties window.• Select the welcomeLabel control and change its Text property to “Deitel and Associates” (Fig. 5.26).

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Text property

Fig. 5.26 | Properties window used to set a property value.

Page 96: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

96

• Return to the Designer code (Fig. 5.27).• Note that the Label’s Text property is now

assigned the text that you entered in the Propertieswindow.

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Text

property

Fig. 5.27 | Windows Form Designer–generated code reflecting new property value.

Page 97: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

97

• Double click the Form’s background in design view (Fig. 5.28).

• Event handlers such as this method are called in response to events.

– In this case, loading the Form occurs when the application begins.

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Fig. 5.28 | Method ASimpleProgramForm_Load created when Form is double clicked.

Page 98: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

98

• Add the statement welcomeLabel.Text ="Visual Basic!" to the method (Fig. 5.29).

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Fig. 5.29 | Method ASimpleProgramForm_Load containing program code.

Page 99: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

99

• The property value is only changed when themethod is called at runtime.

• Run the program (Fig. 5.30).

5.15 Visual Basic Programming in a Windows Forms Application (Cont.)

Fig. 5.30 | Changing a property value at runtime.

Text property of Labelset at runtime

Page 100: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

100

Identifying Attributes• For each descriptive word in the requirements document

that plays a significant role, we create an attribute (Fig. 5.31).

Fig. 5.31 | Descriptive words and phrases from the ATM requirements document. (Part 1 of 2.)

Class Descriptive words and phrases

ATM user is authenticated

BalanceInquiry account number

Withdrawal account number amount

Deposit account number amount

5.16 Software Engineering Case Study: Identifying Class Attributes in the ATM System

Page 101: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

101

Class Descriptive words and phrases

BankDatabase [no descriptive words or phrases]

Account Account number PIN balance

Screen [no descriptive words or phrases]

Keypad [no descriptive words or phrases]

CashDispenser begins each day loaded with 500 $20 bills

DepositSlot [no descriptive words or phrases]

Fig. 5.31 | Descriptive words and phrases from the ATM requirements document. (Part 2 of 2.)

5.16 Software Engineering Case Study: Identifying Class Attributes in the ATM System (Cont.)

Page 102: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

102

• Class ATM maintains information about the state of the ATM. The phrase “user is authenticated” describes a state of the ATM, so we include userAuthenticated as a Boolean attribute.

• Classes BalanceInquiry, Withdrawal and Deposit involve an “account number”.

• Balances and other monetary amounts should be represented by Decimal variables.

5.16 Software Engineering Case Study: Identifying Class Attributes in the ATM System (Cont.)

Page 103: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

103

Modeling Attributes

5.16 Software Engineering Case Study: Identifying Class Attributes in the ATM System (Cont.)

Fig. 5.32 | Classes with attributes.

Page 104: Control Statements: Part 1personal.kent.edu/~asamba/tech46330/Chap05.pdf · 4. OBJECTIVES To use the compound assignment operators to abbreviate assignment operations. To use counter-controlled

2009 Pearson Education, Inc. All rights reserved.

104

userAuthenticated : Boolean = False

– The attribute name is userAuthenticated.– The attribute type is Boolean.– The initial value is False.

5.16 Software Engineering Case Study: Identifying Class Attributes in the ATM System (Cont.)

Software Engineering Observation 5.8Early in the design process classes often lack attributes (and operations). Such classes should not necessarily be eliminated, however, because attributes (and operations) may becomeevident in the later phases of design and implementation.