480 likes | 677 Vues
Introduction to Problem Solving & Control Statements: Part 2. Chapter 6. Quotes for Today. Who can control his fate? William Shakespeare, Othello Intelligence…is the faculty of making artificial objects, especially tools to make tools. Henri Bergson. Loops.
E N D
Introduction to Problem Solving & Control Statements: Part 2 Chapter 6 Rev. Fall 2011-VBN2010-05
Quotes for Today Who can control his fate? William Shakespeare, Othello Intelligence…is the faculty of making artificial objects, especially tools to make tools. Henri Bergson Rev. Fall 2011-VBN2010-05
Loops Repetition & Iteration Rev. Fall 2011-VBN2010-05
Repetition Structures Iteration or The Loops continued Rev. Fall 2011-VBN2010-05
Looping Process - Again • Initialization Count = 0 • set the Loop Control Variable to an initial value • Test (Condition) Count <= 10 • tested before the start of each loop repetition, called the iteration or pass. • Increment Count = Count + 1 • updates the variable during each iteration • must be within the loop body is and is usually the last line • failure to include causes an infinite loop Rev. Fall 2011-VBN2010-05
Now… More Loops Rev. Fall 2011-VBN2010-05
Repetition Statements • Also known as looping statements • While..End Whilestatement • Do While…Loop statement • Do…Loop While statement • Do Until…Loop statement • Do…Loop Until statement • For…Next statement • For Each…Next statement So…Why so many? Legacy software See Notes Section for more info Rev. Fall 2011-VBN2010-05
Another Sample Procedure Note consistent alignment of comments Private Sub cmdButton_click() Dim counter As Integer counter = 2 ‘Initialization Do While counter <= 20 ‘Repetition condition lstOutput.Items.Add(counter) counter = counter + 2 ‘Increment Loop End Sub Space Space Space Rev. Fall 2011-VBN2010-05
The For/Next Loop Rev. Fall 2011-VBN2010-05
The For/Next Loop • Combines all of the Loop Process components into one statement. • Notes on the Counter: • Can be used but must not be modified within the loop body. • Should be a local variable. • The loop body will not be executed if initial is greater than the final value. Rev. Fall 2011-VBN2010-05
The For/Next Loop Syntax For counter = initialTo final [Stepincrement] Next counter • For, To, Step, and Next are Reserved Words • counter is a counter-controlled variable with local type inference (scope). • initialis the initial value of the counter-controlled variable • finalis the value of the counter-controlled variable against which the current value of the counter is tested – equivalent to “<=” • increment is the amount the counter-controlled variable will be incremented after each pass through the loop Rev. Fall 2011-VBN2010-05
For…NextRepetition Statement • Handles counter-controlled-repetition details • Format: Forcounter = initializationTofinalValueStepincrement statement Next counter • If Step is omitted, the default increment is 1 • If the counter is initialized in the For…Next header, then that variable has a scope of that loop. • Can usually be rewritten as: initializationWhilevariable <= finalValuestatementincrementEnd While Rev. Fall 2011-VBN2010-05
Sample Program Private Sub cmdButton_click() Dim counter As Integer ‘ Initialization, repetition condition, and ‘ increment are all performed within the ‘ For structure header. For counter = 2 To 10 Step 2 lstOutput.Items.Add(counter) Nextcounter End Sub Although not technically required in VB.Net 2010, use it in this class! Rev. Fall 2011-VBN2010-05
The For/Next Loop • The starting value, the ending value and the increment portions of a For/Next loop can contain arithmetic expressions. • Ex. X = 2 and y = 10 For j = x To 4 * x * y Step y \ x is equivalent to the statement For j = 2 To 80 Step 5 Rev. Fall 2011-VBN2010-05
The For/Next Loop • The increment can be negative so that the loop actually counts downwards • a decrementing loop • The Step option is used with a negative value for the increment. • Ex. For j = 10 To 1 Step -2 Rev. Fall 2011-VBN2010-05
Flowchart Example For counter = 2 To 10 Step 2 lstOutput.Items.Add(counter) Next counter Note that the “To” is equivalent to “while less than or equal to” counter = 2 counter <= 10 True lstOutput.Items.Add(counter) counter = counter + 2 (implicit) (implicit) False Rev. Fall 2011-VBN2010-05
For Syntax Don’t forget the “Next” at the end of the statement… Rev. Fall 2011-VBN2010-05
For..Next Statement Activity Diagram Rev. Fall 2011-VBN2010-05
Examples Using the For…Next Statement • Varying control variable in For…Next headers • Vary control variable from 1 to 100 in increments of 1 • Fori = 1To100Step1 • Vary control variable from 100 to 1 in increments of –1 • Fori = 100To1Step-1 • Vary control variable from 7 to 77 in increments of 7 • Fori = 7To77Step7 • Vary control variable from 20 to 2 in decrements of 2 • Fori = 20To2Step-2 • Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20 • Fori = 2To20Step3 • Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0 • Fori = 99To0Step-11 Rev. Fall 2011-VBN2010-05
True True y x False False The Nested For/Next Loop • Loops (like if statements) can be nested. • Ex. For x = 1 to 3 For y = 1 to 3 lblOutput.Text = “*” Next y lblOutput.Text = “” Next x *** *** *** What does it do? Rev. Fall 2011-VBN2010-05
Local Type Inference • For example, in the declaration Dim x = 7 the compiler infers that the variable x should be of type Integer, because the compiler assumes that whole-number values, like 7, are Integer values. In the declaration Dim y = -123.45 the compiler infers that the variable y should be of type Double, because the compiler assumes that floating-point literals, like -123.45, are Double values. Rev. Fall 2011-VBN2010-05
Local Type Inference • In the declaration Dim z = 987.65D the compiler infers that the variable z should be of type Decimal, because the value 987.65 is followed by the literal type character D, which indicates that the value is of type Decimal. Some common literal type characters include C for Char ("T"C), F for Single (123.45F), S for Short (123S) and L for Long (123L). Rev. Fall 2011-VBN2010-05
Now for Two More Loops Do/Loop While & Do/Loop Until Rev. Fall 2011-VBN2010-05
Do/Loop WhileRepetition Structure • Similar to the Do While/Loop structure • In the Do While/Loop • loop-continuation is tested at the beginning of the loop before the body of the loop is performed. • In the Do/Loop While • loop-continuation is tested after the loop body is performed, thus executing the loop body at least once. Rev. Fall 2011-VBN2010-05
Do/Loop While • Syntax: Do statements increment counterVariable Loop WhiletestCondition Rev. Fall 2011-VBN2010-05
counter = 1 Action occurs before Test Print counter Counter += 1 counter <= 10 True False Do/Loop While Example Private Sub cmdPrint_Click() Dim counter As Integer counter = 1 Do lstOutput.Items.Add _ (counter) counter = counter + 1 Loop While counter <= 10 End Sub Note Rev. Fall 2011-VBN2010-05
Do..Loop While UML Activity Diagram False Rev. Fall 2011-VBN2010-05
Do/Loop Until Repetition Structure • Similar to the Do Until/Loop structure • In the Do Until/Loop • loop-continuation is tested at the beginning of the loop before the body of the loop is performed. • In the Do/Loop Until • loop-continuation is tested after the loop body is performed, thus executing the loop body at least once. Rev. Fall 2011-VBN2010-05
Do/Loop Until • Syntax: Do statements increment counterVariable Loop UntiltestCondition Rev. Fall 2011-VBN2010-05
counter = 1 Action occurs before Test Print counter Counter += 1 counter = 10 False True Do/Loop Until Example Private Sub cmdPrint_Click() Dim counter As Integer counter = 1 Do lstOutput.Items.Add _ (counter) counter = counter + 1 Loop Until counter = 10 End Sub Rev. Fall 2011-VBN2010-05
Do..Loop UntilUML Activity Diagram False Rev. Fall 2011-VBN2010-05
Loop Comparisons • While/End While is equal to Do While/Loop and both test for truth • Do While/Loop is related Do/Loop While by Do While tests at top and Do/Loop While tests at bottom and both test for truth • Do Until/Loop is related Do/Loop Until by Do Until tests at top and Do/Loop Until tests at the bottom but both test for falsity • While/End While & Do While/Loop are the logical opposite to the Do Until/Loop Rev. Fall 2011-VBN2010-05
The Case Statement Rev. Fall 2011-VBN2010-05
The Case Statement • Is similar to a Multiple Selection If/Then/Else statement. • Uses Positive Logic • Syntax: Select Casetestvalue Casevalue1 statement group 1 Casevalue2 statement group 2 End Select Rev. Fall 2011-VBN2010-05
Case Flow Chart True Case a Case a action False True Case b Case b action False Case Else Case Else action Rev. Fall 2011-VBN2010-05
Case Example But what is the problem with this code? Select Case Grade Case 90..100 LetterGrade = “A” Case 80..89.9 LetterGrade = “B” Case 70..79.9 LetterGrade = “C” Case 60..69.9 LetterGrade = “D” Else LetterGrade = “F” End Select Rev. Fall 2011-VBN2010-05
Case Usage • Used for menu-driven programs and event-driven programs • Menu • A list of options that a program based on case logic can perform • Event-driven • Order is dictated by the user, not the programmer, by which button is clicked on Rev. Fall 2011-VBN2010-05
Good Programming Practices • Indent! • The loop • The statements within a loop • Spacing! • Before and after a loop • Before and after a multiple-line comment • Include the loop control variable’s name after Next in a For/Next Loop Rev. Fall 2011-VBN2010-05
Good Programming Practice • In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value. • Do not use -1 Rev. Fall 2011-VBN2010-05
Common Programming Errors Rev. Fall 2011-VBN2010-05
Common Programming Errors • Trying to control counter-controlled loops with a floating-point value. • Use Integers instead • Confusing a Selection statement with a Repetitive Statement • Selection statements only occur once • Repetitive statements may occur once, but are able to repeat any number of times. Rev. Fall 2011-VBN2010-05
Common Programming Errors • Run-time Errors: • Placing a larger value on the left side of keyword To in a Case statement is a logic error and is consequently ignored at run-time. • Assigning a value to a constant variable in an executable statement. Rev. Fall 2011-VBN2010-05
Common Programming Errors • Syntax Errors: • Using the wrong variable name in a Next statement • Not terminating a For/Next with Next • Attempting to declare a constant variable without assigning it a value in the declaration. • Using Dim with Const in a declaration. Rev. Fall 2011-VBN2010-05
Common Programming Errors • Logic errors: • Duplicate Case statements are logic errors. At run time, the first matching Case is executed. • If the value on the left side of the To keyword in a Case statement is larger than the value on the right side, the Case is ignored during program execution; this is probably a logic error. Rev. Fall 2011-VBN2010-05
Common Programming Errors • Bad Things to Do • Changing the value of the Counter within a loop. • When the loop counter is supposed to be incrementing, the increment value is a negative. (and vice versa) • Avoid using Single or Double as count-controlled loops counters. Rev. Fall 2011-VBN2010-05
Common Programming Errors • Using an incorrect relational operator or using an incorrect final value of a loop counter in the condition of a Do Until/Loop or Do/Loop Until structure can cause off-by-one errors. Rev. Fall 2011-VBN2010-05
Next? Procedures & Functions & Recursion Rev. Fall 2011-VBN2010-05