Visual Basic 2010 Express Visual Basic 2010 How to Program Dr. Isaac Gang Tuesday February 15, 2011 Lecture 4 notes

Topics: -

Problem-solving Techniques If…then and if…then…else selection statements While…end while, Do while…loop, and Do until…loop repetition statements Compound assignment operators Counter-controlled repetition and nested control statements VB debugger

Intro: Before writing a program to solve a problem, you should have a thorough understanding of the problem and a carefully planned approach. When writing a program, it’s also important to know the available building blocks and to use proven program-construction principles. In this lecture, we will look at the theory and principles of structured programming with control statements. We introduce the If…Then, If…Then…Else, Do While…Loop, While…End While and Do Until…Loop statements—five of the building blocks that allow you to specify the logic required for methods to perform their tasks. We introduce the ListBox control and use it to display and process data, such as a list of grades in a class-average program. We also demonstrate how to “stack” and “nest” control statement to solve problems. We conclude with an introduction to the Visual Studio debugger. You’ll learn how to view the values of variables during a program’s execution, how to step through code one statement at a time and how the debugger can help you locate logic errors in your programs.

Problem solving: Any computing problem can be solved by executing a series of actions in a specific order. ◦ A procedure for solving a problem, in terms of the actions to be executed and the order in which these actions are to be executed is called an algorithm. The following example demonstrates the importance of getting the order right. 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. This routine prepares the executive for a productive day at the office. However, suppose that the same steps are performed 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. CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

Specifying the order in which statements (actions) execute in a program is called program control. These notes examine program control using control statements. Pseudocode is an informal language that helps you develop algorithms. It’s similar to everyday English; it’s convenient and user friendly, but not an actual computer programming language. The pseudocode we present is particularly useful for developing algorithms that will be converted to structured portions of Visual Basic programs. Pseudocode programs are not executed on computers. Rather, they help you “think out” a program before writing it in a programming language. You can easily convert a carefully prepared pseudocode program to a corresponding Visual Basic program. Pseudocode normally describes only statements representing the actions that occur after you convert a program from pseudocode to Visual Basic and run the program on a computer.Such actions might include input, output or calculations. Normally, statements in a program are executed one after another in the order in which they’re written. This is called sequential execution. A transfer of control occurs when an executed statement does not directly follow the previously executed statement. Research demonstrated that all programs could be written in terms of only three control structures—the sequence structure, the selection structure and the repetition structure. The term “control structures” comes from the field of computer science. When we introduce Visual Basic’s implementation of control structures, we’ll refer to them as “control statements.” Sequence Structure Unless directed otherwise, the computer executes statements sequentially. Selection Statements Visual Basic provides three types of selection statements. ◦ The If…Then selection statement either performs (selects) an action (or sequence of actions) if a condition is true, or skips the action (or sequence of actions) if the condition is false. The If…Then statement is called a single-selection statement because it selects or ignores a single action (or a sequence of actions). ◦ The If…Then…Else selection statement performs an action (or sequence of actions) if a condition is true, and performs a different action (or sequence of actions) if the condition is false. The If…Then…Else statement is called a doubleselection statement because it selects between two different actions (or sequences of actions). ◦ The Select…Case selection statement performs one of many possible actions (or sequences of actions), depending on the value of an expression. For this reason, the Select…Case statement is called a multiple-selection statement. Repetition Statements Visual Basic provides seven types of repetition statements (also called looping statements or loops) that enable programs to perform statements repeatedly based on the value of a condition. ◦ The Do While…Loop and While…End While repetition statements execute a set of statements while a condition—known as the loop-continuation condition— CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

remains true. If the condition is initially false, the set of statements does not execute. ◦ The Do Until…Loop repetition statement executes a set of statements until a condition—known as the loop-termination condition—becomes true. If the condition is initially true, the set of statements does not execute. ◦ The Do…Loop While repetition statement executes a set of statements while its loop-continuation condition remains true. The set of statements is guaranteed to execute at least once. ◦ The Do…Loop Until repetition statement executes a set of statements until its loop-termination condition becomes true. The set of statements is guaranteed to execute at least once. ◦ The For…Next repetition statement executes a set of statements a specified number of times—this is known as counter-controlled (or definite) repetition. ◦ The For Each…Next repetition statement (will be examined more in later notes) performs a set of statements for every element of a so-called array or collection of values. The words If, Then, Else, End, Select, Case, While, Do, Until, Loop, For, Next and Each are all keywords. By providing many repetition statements, the designers of Visual Basic make it more convenient for you to express certain types of algorithms. Theoretically, however, you need only one repetition statement that enables you to loop zero or more times based on the truth or falsity of a condition—both Do While…Loop and While…End While allow you to do this. A selection statement chooses among alternative courses of action. Suppose that the passing grade on an examination is 60 (out of 100).Then the pseudocode statement If student’s grade is greater than or equal to 60 then Display “Passed” determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, then “Passed” is displayed, and the next pseudocode statement in order is “performed” (remember that pseudocode is not a real programming language). If the condition is false, the display statement is ignored, and the next pseudocode statement in order is “performed.” The preceding pseudocode If statement may be written in Visual Basic as  If studentGrade >= 60 Then resultLabel.Text = "Passed" ' display "Passed" End If The code corresponds closely to the pseudocode, showing the usefulness of pseudocode as a program-development tool. The statement in the body of the If…Then statement displays the string "Passed" on resultLabel. The If…Then…Else selection statement allows you to specify that a different action (or sequence of actions) is to be performed when the condition is true than when the condition is false. CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

For example, the pseudocode statement If student’s grade is greater than or equal to 60 then Display “Passed” Else Display “Failed” displays “Passed” if the student’s grade is greater than or equal to 60, and displays “Failed” if the student’s grade is less than 60. In either case, after the display occurs, the next pseudocode statement in sequence is “performed.” The preceding pseudocode If…Else statement may be written in Visual Basic as  If studentGrade >= 60 Then resultLabel.Text = "Passed" ’ display "Passed" Else resultLabel.Text = "Failed" ’ display "Failed" End If The body of the Else clause is indented so that it lines up with the body of the If clause. Nested If…Then…Else statements test for multiple conditions by placing If…Then …Else statements inside other If…Then…Else statements. For example, the pseudocode below displays “A” for exam 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 grades in the range 60–69 and “F” for all other grades.

The pseudocode may be written in Visual Basic as

CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

ElseIf Most programmers prefer to write the nested If…Then…Else statements from Fig. 4.4 using the ElseIf keyword as shown in Fig. 4.5. Both forms are equivalent, but the latter is popular because it avoids deeply indenting the code and makes it more readable. In nested If…Then…Else statements, if you type Else If on one line, the Visual Basic editor will automatically convert it to ElseIf and indent the code as in Fig. 4.5.

CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

A repetition statement (also called a looping statement, an iteration statement or a loop) allows you to specify that an action should be repeated, depending on the value of a loopcontinuation condition or a loop-termination condition. The pseudocode statements While there are more items on my shopping list Put next item in cart Cross it off my list describe the repetitive actions on a shopping trip. The loop-continuation condition “there are more items on my shopping list” can be true or false. If it’s true, the actions “Put next item in cart” and “Cross it off my list” are performed. These actions execute repeatedly while the condition remains true. The statement(s) contained in the While repetition statement constitute the body of the While. Eventually, the condition becomes false (when the last remaining item on the shopping list has been purchased and crossed off the list). Then, the repetition terminates, and the first statement after the repetition statement executes. Consider a program segment designed to find the first power of 3 larger than 100. Suppose that the Integer variable product is initialized to 3. When the following Do While…Loop statement finishes executing, product contains the result:  Do While product 100 product = product * 3 ' compute next power of 3 Loop CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

Because we’re using a Do Until…Loop statement, the statement’s action is performed when the statement’s loop-termination condition is false (that is, product is less than or equal to 100). When the loop-termination condition (product > 100, the leftmost guard condition) is true, the statement exits. If the condition in a Do Until…Loop is initially true, the body statement(s) do not execute. In general, you can use a Do While…Loop statement with the condition expressed differently (in this case product Insert Breakpoint. Additionally, you can click a line of code then press F9 to toggle a breakpoint on and off for that line of code. You may set as many breakpoints as you like. A solid circle appears in the margin indicator bar where you clicked and the entire code statement is highlighted, indicating that a breakpoint has been set. After setting breakpoints in the code editor, select Debug > Start Debugging (or press the F5 key) to rebuild the program and begin the debugging process. Enter the grades 100, 97 and 88, then press the Calculate Class Average button. When the debugger reaches line 28 (the line that contains the breakpoint), it suspends execution and enters break mode At this point, the IDE becomes the active window. The yellow arrow to the left of line 28—called the instruction pointer—indicates that this line contains the next statement to execute. The IDE also highlights the line as well to emphasize the line that is about to execute. In break mode, you can place the mouse cursor over any variable and its value will be displayed in a Quick Info box. This can help you spot logic errors. While in break mode, you can also explore the values of a method’s local variables using the debugger’s Locals window . To view the Locals window, select Debug > Windows > Locals.

CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

Recall that all variables in Visual Basic get initialized, so even though lines 28–29 have not executed yet, variables total and gradeCounter currently have the value 0 (the default for Integer variables). You’ll now execute the program one statement at a time using the debugger’s Step Over command. You can access this command by selecting Debug > Step Over, by pressing Shift + F8 or by pressing the Step Over command’s toolbar icon (). Do this twice now. The instruction pointer arrow now points to the Do While…Loop statement’s first line. If you position the mouse over the word Count in gradesListBox.Items.Count, you can see in the Quick Info window that the number of items in the ListBox is 3. Similarly, you can place the mouse over variable gradeCounter to see that its value is currently 0. At this point in the program’s execution, the user cannot add more items to the ListBox because we’ve disabled the TextBox and Button that allow the user to enter a grade, so gradesListBox.Items.Count will remain as 3. Thus, the loop should execute the statements at lines 33–35 a total of three times to process the three grades. Since gradeCounter’s value is less than or equal to 3, the condition in line 32 is true. Thus, when you use the Step Over command again, the instruction pointer moves to line 33 in the loop’s body. Now use the Step Over command to execute line 33. The first item in the ListBox (100) is assigned to variable grade, which you can see in the Quick Info box and in the Locals window. Whenever a variable’s value is modified as a result of the last statement to execute, the Locals window highlights that value in red. Now, Step Over lines 34 and 35 to add the grade to the total and to add 1 to the gradeCounter. The instruction pointer is now aimed at line 36. When you use the Step Over command now, the instruction pointer moves back to the top of the loop so the condition can be tested again.Variable gradeCounter’s value is now 1, so the condition is still true, thus the loop’s body will execute again. Use the Step Over command five times to step through this iteration of the loop, which adds the grade 97 to the total, increments gradeCounter to 2 and positions the instruction counter at the top of the loop. Variable gradeCounter’s value is now 2, so the condition is still true, thus the loop’s body will execute again so we can process the last grade. Use the Step Over command five times to step through this iteration of the loop, which adds the grade 88 to the total, increments gradeCounter to 3 and positions the instruction counter at the top of the loop. At this point, we’ve processed all three grades and the loop should terminate. However, gradeCounter’s value is 3, which is less than or equal to 3. The condition is still true—even though we are done processing the three grades. Thus, the loop will attempt to process another grade, even though one does not exist. This is the logic error. When you Step Over line 33 again, you get the error shown in Fig. 4.17. CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.

Stepping through the program in this manner enables you to see that the loop’s body executes four times when it should only execute three times. So we can focus on the loop’s condition as the source of the logic error, because the condition determines when the loop should stop executing. To correct the error, you can stop the debugger by selecting Debug > Stop Debugging, then edit the code by changing the Disable Breakpoint, then run the program; ◦ Remove each breakpoint by right clicking the breakpoint and selecting Delete Breakpoint, then run the program; or Execute the program without debugging by pressing Ctrl + F5.

CSS331 Lecture Notes: © Dr. Isaac Gang, 2011.