Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Statements: Part 1

Similar presentations


Presentation on theme: "Control Statements: Part 1"— Presentation transcript:

1 Control Statements: Part 1
5 Control Statements: Part 1

2 Let’s all move one place on.
Lewis Carroll The wheel is come full circle. William Shakespeare, King Lear How many apples fell on Newton’s head before he took the hint? Robert Frost All the evolution we know of proceeds from the vague to the definite. Charles Sanders Peirce

3 OBJECTIVES In this chapter you will learn:
Basic problem-solving techniques. To develop algorithms through the process of top-down, To develop algorithms through the process of top-down, To use the IF…Then and IF…Then…Else selection statements to choose among alternative actions. To use the While, Do While…Loop and Do Until…Loop repetition statements to execute statements in a program repeatedly. 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 application.

4 5.1   Introduction 5.2   Algorithms 5.3   Pseudocode 5.4   Control Structures 5.5   If...Then Selection Statement 5.6   If...Then...Else Selection Statement 5.7   While Repetition Statement 5.8   Do While...Loop Repetition Statement 5.9   Do Until...Loop Repetition Statement 5.10   Compound Assignment Operators

5 5.11   Formulating Algorithms: Counter-Controlled Repetition
5.12   Formulating Algorithms: Sentinel-Controlled Repetition 5.13 Formulating Algorithms: Nested Control Statements 5.14   Formulating Algorithms: Nested Repetition Statements 5.15   Visual Basic Programming in a Windows Application 5.16   (Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System 5.17   Wrap-Up

6 5.1 Introduction It is essential to have a thorough understanding of the problem and a carefully planned approach before writing a program. It is equally important to recognize the types of building blocks that are available and to employ proven program-construction principles. Control statements are important in building and manipulating objects.

7 5.2 Algorithms Algorithms Program control The actions to execute
The order in which these actions execute Program control Specifies the order in which actions execute in a program

8 5.3 Pseudocode Pseudocode An informal language similar to English
Helps programmers develop algorithms Does not run on computers Should contain input, output and calculation actions Should not contain variable declarations

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

10 5.4 Control Structures Sequential execution Transfer of control
Statements are executed one after the other in the order in which they are written Transfer of control Specifying the next statement to execute that is not necessarily the next one in order Can be performed by the GoTo statement Structured programming eliminated GoTo statements

11 5.4 Control Structures (Cont.)
Bohm and Jacopini’s research Demonstrated that GoTo statements were unnecessary Demonstrated that all programs could be written with three control structures Sequence structure Selection structure Repetition structure

12 5.4 Control Structures (Cont.)
UML activity diagram ( Models the workflow (or activity) of a part of a software system Action-state symbols (rectangles with their sides replaced with outward-curving arcs) Represent action expressions specifying actions to perform Diamonds Decision symbols (explained in section 5.5) Merge symbols (explained in section 5.7)

13 5.4 Control Structures (Cont.)
Small circles Solid circle represents the activity’s initial state Solid circle surrounded by a hollow circle represents the activity’s final state Transition arrows Indicate the order in which actions are performed Notes (rectangles with the upper-right corners folded over) Explain the purposes of symbols (like comments in VB) Are connected to the symbols they describe by dotted lines

14 Fig. 5.1 | Sequence-structure activity diagram.

15 5.4 Control Structures (Cont.)
Selection Statements If…Then statement Single-selection statement If…Then…Else statement Double-selection statement Select…Case statement Multiple-selection statement

16 5.4 Control Structures (Cont.)
Repetition statements Also known as looping statements While statement Do While…Loop statement Do…Loop While statement Do Until…Loop statement Do…Loop Until statement For…Next statement For Each…Next statement

17 5.4 Control Structures (Cont.)
Visual Basic has three kinds of control structures Sequence statement Selection statements (3 types) Repetition statements (7 types) All programs are composed of these control statements Control-statement stacking All control statements are single-entry/single-exit Control-statement nesting One control statement is placed inside another

18 Software Engineering Observation 5.2
Any 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).

19 5.5 If…Then Single-Selection Statement
If…Then statements Execute an action if the specified condition is True Can be represented by a decision symbol (diamond) in a UML activity diagram Transition arrows out of a decision symbol have guard conditions Workflow follows the transition arrow whose guard condition is true

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

21 5.5 If…Then Single-Selection Statement
Errors Syntax error Caught by complier Logic error Affect the program only at execution time Fatal logic error Causes program to fail and terminate prematurely Nonfatal logic error Does not terminate a program’s execution but causes the program to produce incorrect results

22 5.6 If…Then…Else Double-Selection Statement
If…Then…Else statement Executes one action if the specified condition is True or a different action if the specified condition is False Nested If…Then…Else statements If…Then…Else statements can be put inside other If…Then…Else statements Keyword ElseIf can be used to imitate nested If…Then…Else statements

23 Good Programming Practice 5.1
Indent both body statements of an If...Then...Else statement to improve readability.

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

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

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

27 5.7 While Repetition Statement
While statement Repeats an action while its loop-continuation condition remains true Uses a merge symbol in its UML activity diagram Merges two or more workflows Represented by a diamond (like decision symbols) but has: Multiple incoming transition arrows, Only one outgoing transition arrow and No guard conditions on any transition arrows

28 Outline PowersOfThree.vb The while loop will continue executing if its condition evaluates to true: if product is less than or equal to 100

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

30 Fig. 5.5 | While repetition statement activity diagram.

31 5.8 Do While…Loop Repetition Statement
The Do While…Loop statement behaves like a While statement.

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

33 Outline DoWhile.vb The Do While…Loop statement will continue executing if its condition evaluates to true: if product is less than or equal to 100

34 5.9 Do Until…Loop Repetition Statement
The Do Until…Loop statement is executed repeatedly as long as the condition evaluates to false.

35 Outline DoUntil.vb The Do Until…Loop statement will continue executing if its condition evaluates to false: if product is less than or equal to 100

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

37 5.10 Compound Assignment Operators
An assignment statement of the form: variable = variable operator expression where operator is +, -, *, /, \, ^ or & can be written as: variable operator= expression example: c = c + 3 can be written as c += 3 This statement adds 3 to the value in variable c and stores the result in variable c

38 Fig. 5.8 | Compound assignment operators.

39 Outline Assignment.vb Using the ^= compound assignment operators to calculate the exponent value

40 5.11 Formulating Algorithms: Counter-Controlled Repetition
Also known as a definite repetition Use a counter variable to count the number of times a loop is iterated Integer division The fractional part of an integer division calculation is truncated (thrown away)

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

42 Fig | Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

43 Outline (1 of 3 ) Assign a value to instance variable courseNameValue
GradeBook.vb (1 of 3 ) Assign a value to instance variable courseNameValue Declare property CourseName

44 Outline GradeBook.vb (2 of 3 )

45 Outline Declare method DetermineClassAverage (3 of 3 )
GradeBook.vb (3 of 3 ) Counter to control while loop Initialize gradeCounter to 1 While loop iterates as long as gradeCounter <= 10 Increment the counter variable gradeCounter Calculate average grade Display results

46 Good Programming Practice 5.5
Separating declarations from other statements with a blank line improves readability.

47 Software Engineering Observation 5.3
Experience has shown that the 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.

48 Outline Create a new GradeBook object
GradeBookTest.vb Pass the course’s name to the GradeBook constructor as a string Call GradeBook’s DetermineClassAverage method

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

50 5.12 Formulating Algorithms: Sentinel-Controlled Repetition
Also known as indefinite repetition Use a sentinel value (also known as a signal, dummy or flag value) A sentinel value cannot also be a valid input value

51 Common Programming Error 5.5
Choosing a sentinel value that is also a legitimate data value could result in a logic error that would cause a program to produce incorrect results.

52 5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)
Top-down, stepwise refinement Top step: a single statement that conveys the overall function of the program First refinement: multiple statements using only the sequence structure Second refinement: commit to specific variables, use specific control structures

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

54 Software Engineering Observation 5.5
Many algorithms can be divided logically into three phases—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.

55 Error-Prevention Tip 5.1 When 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. Sometimes more sophisticated processing is required, such as using the techniques of Chapter 12, Exception Handling.

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

57 Software Engineering Observation 5.6
You terminate the top-down, stepwise refinement process when the pseudocode algorithm is specified in sufficient detail for the pseudocode to be converted to a Visual Basic program.

58 Fig. 5.13 | Class-average problem pseudocode algorithm with sentinel-controlled repetition.

59 Outline (1 of 4 ) Assign a value to instance variable courseNameValue
GradeBook.vb (1 of 4 ) Assign a value to instance variable courseNameValue Declare property CourseName

60 Outline GradeBook.vb (2 of 4 ) Declare method DisplayMessage

61 Outline Declare method DetermineClassAverage (3 of 4 )
GradeBook.vb (3 of 4 ) Declare local Integer variables total, gradeCounter and grade and Double variable average While loop iterates as long as grade <> the sentinel value, -1

62 Outline GradeBook.vb (4 of 4 ) Calculate average grade using / operator for a floating point number Display average grade Display “No grades were entered” message

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

64 5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)
Floating-point numbers (Approximations) Single (Single-Precision) Double (Double-Precision) Stores numbers with greater magnitude and precision than Single Decimal Stores a limited range of real numbers precisely The / operator will perform an implicit promotion of the operands to Doubles.

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

66 5.12 Formulating Algorithms: Sentinel-Controlled Repetition (Cont.)
Format Specifier {0: F} F = real number # to the right of F is the precision Example: Dim number As Double = Console.WriteLine(“OUTPUT: {0:F3}”, number) OUTPUT: 3.123

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

68 Fig. 5.15 | Formatting codes for Strings.

69 Outline Create a new GradeBook object
GradeBookTest.vb Pass the course’s name to the GradeBook constructor as a String Call GradeBook’s DetermineClassAverage method

70 5.13 Formulating Algorithms: Nested Control Statements
Control statements can be nested within one another Place one control statement inside the body of the other

71 Fig. 5.17 | Pseudocode for examination-results problem.

72 Outline Declare ProcessExamResults’ local variables (1 of 2 )
Analysis.vb (1 of 2 ) While loop iterates as long as studentCounter <= 10 Determine whether this student passed or failed and increment the appropriate variable

73 Outline Determine whether more than eight students passed the exam
Analysis.vb (2 of 2 )

74 Outline Create a new Analysis object
AnalysisTest.vb Call Analysis’s ProcessExamResults method

75 5.14 Formulating Algorithms: Nested Repetition Statements
Repetition statements can be nested within one another Place one repetition statement inside the body of the other

76 Fig. 5.20 | Second refinement of the pseudocode.

77 Software Engineering Observation 5.7
Many 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 delays in large, complex projects.

78 Outline Box.vb (1 of 2 )

79 Outline Box.vb (2 of 2 ) Nested While loop to iterate through every column of every row

80 Outline BoxTest.vb (1 of 2 ) Call method Display which uses nested repetition statements

81 Outline BoxTest.vb (2 of 2 )

82 Good Programming Practice 5.9
The prefixes Frm, lbl and pic allow Forms, Labels and PictureBoxes, respectively, to be identified easily in program code.

83 5.15 Visual Basic Programming in a Windows Application
Visual Programming When you create a GUI, code is generated by the IDE to define that GUI The code is stored in two files One defines the initial appearance of GUI The other defines the behavior Windows applications use classes (no modules) Every windows application consists of at least one class that inherits from class Form The use of Inherits absorbs the capabilities of class Form which enables you to create Forms quickly and easily. Events State changes Event handlers respond to state changes in the GUI

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

85 Fig. 5.24 | Windows Form Designer generated code.

86 Fig. 5.25 | Property initializations generated by the Windows Form Designer for lblWelcome.

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

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

89 Fig. 5.28 | Method FrmASimpleProgram_Load created when Form is double clicked.

90 Fig. 5.29 | Method FrmASimpleProgram_Load containing program code.

91 Fig. 5.30 | Changing a property value at runtime.

92 5.16  - (Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System
Identifying attributes Look for descriptive words and phrases in the requirements document Create attributes and assign them to classes Each attribute is given an attribute type Some attributes may have an initial value Some classes may end up without any attributes Additional attributes may be added later on as the design and implementation process continues Reference-type attributes are modeled more clearly as associations

93 Fig. 5.31 | Descriptive words and phrases from the ATM requirements document.

94 Fig. 5.32 | Classes with attributes.

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


Download ppt "Control Statements: Part 1"

Similar presentations


Ads by Google