control structures: part 1. introduction control structures if / then selection structure if / then...

42
Control Control Structures: Part 1 Structures: Part 1

Post on 21-Dec-2015

240 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Control Structures: Part 1Control Structures: Part 1

Page 2: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

IntroductionControl Structures If/Then Selection Structure If/Then/Else Selection Structure While Repetition Structure Do While/Loop Repetition Structure Do Until/Loop Repetition Structure Assignment Operators Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition)

OutlineOutline

Page 3: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 3 (Nested Control Structures)Formulating Algorithms with Top-Down, Stepwise Refinement: Case Study 4 (Nested Repetition

Structures) Introduction to Windows Application Programming

Page 4: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Control StructuresControl Structures

• Selection Structures– If/Then

• Single-selection structure

– If/Then/Else• Double-selection structure

– Select Case• Multiple-selection structure

Page 5: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Control StructuresControl Structures

• Repetition Structures– While Loop– Do Loops:

• Do While/Loop• Do/Loop While• Do Until/Loop• Do/Loop Until

– For Loops: • For/Next• For Each/Next

Page 6: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

If//Then Selection StructureSelection Structure

• It is a single-entry/single-exit structure• Example

If studentGrade >= 60 Then

MsgBox(“Passed”)End If

Page 7: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• The preceding The preceding IfIf//Then Then selection structure also could be selection structure also could be written on a single line as written on a single line as

If studentGrade >= 60 Then MsgBox("Passed")If studentGrade >= 60 Then MsgBox("Passed")

• In the multiple-line format, all statements in the body of the In the multiple-line format, all statements in the body of the IfIf//Then Then are executed if the condition is true. are executed if the condition is true.

• In the single-line format, only the statement after the In the single-line format, only the statement after the Then Then keyword is executed if the condition is true.keyword is executed if the condition is true.

• Writing the closing Writing the closing End If End If keywords after a single-line keywords after a single-line IfIf//Then Then structure is a syntax error.structure is a syntax error.

If//Then Selection StructureSelection Structure

Page 8: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

The If/Then/Else selection structure allows the programmer to specify that a different action (or sequence of actions) be performed when the condition is true than when the condition is false.

IfIf//ThenThen//ElseElse Selection Structure Selection Structure

Page 9: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

IfIf//ThenThen//ElseElse Selection Structure Selection Structure

• ExampleIf studentGrade >= 60 Then

MsgBox(“Passed”)Else

MsgBox(“Failed”)End If

Page 10: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• The VB Editor tries to help you write If statements. • When in the code view window, if you type the

keyword If and press Enter, the VB editor automatically adds the keywords Then and End If. You can add the Else branch as necessary.

• The VB editor will try to correct errors. If you type EndIf with no space, the editor will correct this and add the required space.

• If you type Else with a coding statement on the line, the editor will add a colon between Else and the coding statement – the colon is a statement separator.

IfIf//ThenThen//ElseElse Selection Structure Selection Structure

Page 11: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• Illegal SyntaxIf HoursDecimal <= 40D Then MsgBox(“ Equals to 40”)Else MsgBox(“ Not Equals to 40”)End If

• VB Editor Correction with ColonIf HoursDecimal <= 40D Then MsgBox(“ Equals to 40”)Else : MsgBox(“ Not Equals to 40”)End If

• Preferred SyntaxIf HoursDecimal <= 40D Then MsgBox(“Equals to 40”)Else MsgBox(“ Not Equals to 40”)End If

If you type Else with a coding statement on the line, the editor will add a colon between Else and the coding statement

IfIf//ThenThen//ElseElse Selection Structure Selection Structure

Page 12: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• Nested If/Then/Else structures test for multiple conditions by placing If/Then/Else structures inside other If/Then/Else structures.

• Most Visual Basic programmers prefer to write the nested If/Then/Else structure

using the ElseIf keyword.

NestedNested If If//ThenThen//ElseElse

Page 13: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

For example, the following code will print “A” for exam For example, the following code will print “A” for exam grades greater than or equal to 90, “B” for grades in the grades greater than or equal to 90, “B” for grades in the range 80–89, “C” for grades in the range 70–79, “D” for range 80–89, “C” for grades in the range 70–79, “D” for grades in the range 60–69 and “F” for all other grades.grades in the range 60–69 and “F” for all other grades.

NestedNested If/Then/Else If/Then/Else

If grade >= 90 ThenMsgBox(“A”)

ElseIf grade >= 80 ThenMsgBox(“B”)

ElseIf grade >= 70 ThenMsgBox(“C”)

ElseIf grade >= 60 ThenMsgBox(“D”)

Else MsgBox(“F”)

End IF

Page 14: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

While Repetition StructureWhile Repetition Structure

• Repetition structureRepetition structure– Allows the programmer to specify that an action Allows the programmer to specify that an action

should be repeated, depending on the value of a should be repeated, depending on the value of a conditioncondition

Page 15: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Write a program that finds the first power of two larger than 1000?Write a program that finds the first power of two larger than 1000?

Failure to provide the body of the structure with an action that causes the condition to become false creates an infinite loop

Page 16: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Do While/Loop Repetition StructureDo While/Loop Repetition Structure

• This structure behaves like the While repetition structure

Page 17: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

DoWhile.vb

Program Output

Failure to provide the body of the structure with an action that causes the condition to become false creates an infinite loop

Write a program to find the first power of two larger than 1000?Write a program to find the first power of two larger than 1000?

Page 18: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Do Until/Loop Repetition StructureDo Until/Loop Repetition Structure

• Unlike the Unlike the While While and and Do WhileDo While//Loop Loop repetition structures, the repetition structures, the Do UntilDo Until//Loop Loop repetition structure tests a condition for repetition structure tests a condition for falsity for repetition to continue. falsity for repetition to continue.

• Statements in the body of a Statements in the body of a Do UntilDo Until//Loop Loop

are executed repeatedly as long as the are executed repeatedly as long as the loop-continuation test evaluates to false.loop-continuation test evaluates to false.

Page 19: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

DoUntil.vb

Program Output

The loop ends when the condition becomes true

once again consider a program designed to find the first power once again consider a program designed to find the first power of two larger than 1000.of two larger than 1000.

Page 20: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

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

Fig. 4.11 Assignment operators.

Fig. 4.11 Assignment operators.

Assignment OperatorsAssignment Operators

Page 21: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Assignment.vb

Program Output

Calculates a power of two using the exponentiation assignment operator.Calculates a power of two using the exponentiation assignment operator.

Page 22: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• Although the symbols =, +=, -=, *=, /=, \=, ^= and &= Although the symbols =, +=, -=, *=, /=, \=, ^= and &= are operators, we do not include them in operator-are operators, we do not include them in operator-precedence tables. precedence tables.

• When an assignment statement is evaluated,When an assignment statement is evaluated, the expression to the right of the operator is always the expression to the right of the operator is always

evaluated first, then assigned to theevaluated first, then assigned to the variable variable on the left.on the left.• Unlike Visual Basic’s other operators, the Unlike Visual Basic’s other operators, the

assignment operators can only occur once in a assignment operators can only occur once in a statement.statement.

Assignment OperatorsAssignment Operators

Page 23: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Space Counter ExampleSpace Counter Example

Property ReadOnly = true

Page 24: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Public Class Form1Public Class Form1

Private Sub btnCount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCount.Click Dim i, counter As Integer, A As StringDim i, counter As Integer, A As String counter = 0counter = 0

For i = For i = 00 To txtString.Text To txtString.Text.Length .Length - 1- 1 A =A = txtString.TexttxtString.Text.Chars(i).Chars(i) If A = " " ThenIf A = " " Then counter = counter + 1counter = counter + 1 ElseElse txtStringNoSpace.Text = txtStringNoSpace.Text txtStringNoSpace.Text = txtStringNoSpace.Text && A A End IfEnd If Next iNext i txtSpacesNo.Text = countertxtSpacesNo.Text = counter End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click txtString.Clear()txtString.Clear() txtSpacesNo.Text = ""txtSpacesNo.Text = "" txtStringNoSpace.Text = ""txtStringNoSpace.Text = "" End SubEnd ClassEnd Class

Space Counter ExampleSpace Counter Example

Page 25: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Case Study 1 Case Study 1 (Counter-Controlled Repetition)(Counter-Controlled Repetition)

• Counter-controlled repetition– Uses counter: Variable that specifies the number

of times that a set of statements will execute

• Example: A class of ten students took a quiz. The grades

(integers in the range from 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

Page 26: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure
Page 27: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Program OutputProgram Output

Enter integer grade: 89Enter integer grade: 70Enter integer grade: 73Enter integer grade: 85Enter integer grade: 64Enter integer grade: 92Enter integer grade: 55Enter integer grade: 57Enter integer grade: 93Enter integer grade: 67 Class average is 74.5

Page 28: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• Develop a class-averaging program that averages an arbitrary number of grades each time the program is run.

• In the first class-average example, the number of grades (10) was known in advance.

• In this example, no indication is given of how many grades are to be input. The program must process an arbitrary number of grades.

• How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average?

Case Study 2 Case Study 2 (Sentinel-Controlled Repetition)(Sentinel-Controlled Repetition)

Page 29: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• One way to solve this problem is to use a special value called a sentinel value (also called a signal value, a dummy value or a flag value) to indicate “end of data entry.”

• The user inputs all grades and then types the sentinel value to indicate that the last grade has been entered.

• It is crucial to employ a sentinel value that cannot be confused with an acceptable input value.

• Grades on a quiz are normally nonnegative integers, thus –1 is an acceptable sentinel value for this problem.

Case Study 2 Case Study 2 (Sentinel-Controlled Repetition)(Sentinel-Controlled Repetition)

Page 30: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Test division by zero

In sentinel-controlled repetition, a value is read before the program reaches the While structure

print the value of average in the command window as a fixed-point number.

Page 31: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Program OutputProgram Output

Enter Integer Grade, -1 to Quit: 97Enter Integer Grade, -1 to Quit: 97Enter Integer Grade, -1 to Quit: 88Enter Integer Grade, -1 to Quit: 88Enter Integer Grade, -1 to Quit: 72Enter Integer Grade, -1 to Quit: 72Enter Integer Grade, -1 to Quit: -1Enter Integer Grade, -1 to Quit: -1  Class average is 85.67Class average is 85.67

Page 32: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, 10 of the students who completed this course took the licensing examination. The college wants to know how well its students did on the exam. You have been asked to write a program to summarize the results. You have been given a list of the 10 students. Next to each name is written a “P” if the student passed the exam and an “F” if the student failed the exam.

• Your program should analyze the results of the exam as follows:1. Input each exam result (i.e., a “P” or an “F”). Display the message

“Enter result” each time the program requests another exam result.2. Count the number of passes and failures.3. Display a summary of the exam results, indicating the number of

students who passed and the number of students who failed the exam.

4. If more than 8 students passed the exam, print the message “Raise tuition.”

Case Study 3 Case Study 3 (Nested-Control Structure)(Nested-Control Structure)

Page 33: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Identifier vbCrLf is the combination of the carriage return and linefeed characters

The If/Then/Else structure is a nested control. It is enclosed inside the While.

Page 34: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Program OutputProgram Output

Page 35: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Case Study 4 Case Study 4 (Nested-Repetition Structure)(Nested-Repetition Structure)

•Write a program that draws in the command Write a program that draws in the command window a filled square consisting solely of * window a filled square consisting solely of * characters. characters.

•The side of the square (i.e., the number of * The side of the square (i.e., the number of * characters to be printed side by side) should be characters to be printed side by side) should be input by the user and should not exceed 20.input by the user and should not exceed 20.

Page 36: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Three levels of nesting

Page 37: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Program OutputProgram Output

Page 38: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

– In console applications, execution starts from Main. – In Windows applications, if you want a method like

main you must create a method that executes when the form is loaded into memory during program execution.

– Like Main, this method is invoked when the program is run.

– Double-clicking the form in design view adds a method named FrmASimpleProgram_Load to the class, which is responsible for that

Introduction to Windows Application ProgrammingIntroduction to Windows Application Programming

Page 39: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

Fig. 4.29 Method FrmASimpleProgram_Load containing program code.

Introduction to Windows Application ProgrammingIntroduction to Windows Application Programming

Page 40: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

ConclusionConclusion

• Normally, statements in a program are executed one Normally, statements in a program are executed one after another in the order in which they are written. after another in the order in which they are written. This is called This is called sequential execution.sequential execution.

• • Various Visual Basic statements enable the Various Visual Basic statements enable the programmer to specify that the next statement to be programmer to specify that the next statement to be executed might not be the next one in sequence. This executed might not be the next one in sequence. This is called a is called a transfer of control.transfer of control.

• Bohm and Jacopini’s work demonstrated that all Bohm and Jacopini’s work demonstrated that all programs could be written in terms of only three programs could be written in terms of only three control structures—the control structures—the sequence structuresequence structure, the , the selection structureselection structure and the and the repetition structure.repetition structure.

Page 41: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• Failure to provide in the body of a While or Do While/Loop structure an action that eventually causes the condition to become false is a logic error. Normally, such a repetition structure never terminates, resulting in an error called an “infinite loop.”

• Failure to provide the body of a Do Until/Loop structure with an action that eventually causes the condition in the Do Until/Loop to become true creates an infinite loop.

ConclusionConclusion

Page 42: Control Structures: Part 1. Introduction Control Structures If / Then Selection Structure If / Then / Else Selection Structure While Repetition Structure

• In Counter-controlledIn Counter-controlled the number of repetitions the number of repetitions is is knownknown before the loop begins executing. before the loop begins executing.

• In sentinel-controlledIn sentinel-controlled repetition, the number of repetition, the number of repetitions is repetitions is not knownnot known before the loop begins before the loop begins its execution.its execution.

ConclusionConclusion