LESSON 7 Visual Basic Selection (If Statements) If Statement If uses comparison operators to test data values. If uses comparison operator results to test data. If might execute one or more lines of code, depending on the results of the comparison. Before If, the code you wrote executed one statement after another. If lets your program be more decisive and execute only parts of the program under specific circumstances. If a comparison test is true, the body of the If statement executes. If comparisonTest Then ‘One or more Visual Basic statements End If End If lets Visual Basic know where the body of the If statement ends. Suppose that the user enters a sales figure into Sales. The following If computes a bonus amount based on the sales: If Sales > 5000.00 Then Bonus = Sales * .12 End If Visual Basic stores 0 in all numeric variables that you don't first initialize. Therefore, sngBonus has a 0 before the If executes. Once the If executes, the code changes the sngBonus variable only if the value of the txtSales. Text property is more than 5000.00. In a way, the If reads like this: If the sales are more than $5,000.00, then compute a bonus based on that sales value. The body of an If can have more than one statement. The body is often called a block. The following If calculates a bonus, the cost of sales, and a reorder amount based on the value of the txtSales text box entry: Dim Sales, Bonus, curCostOfSales, curReorderCost as Double Sales = Val(txtSales.Text) If (Sales > 5000.00) Then Bonus = Sales * .12 curCostOfSales = Sales * .41 curReorderCost = Sales * .24 End If The three statements that make up the body of the If execute only if the condition Sales > 5000.00 is true. Suppose that this code contains another assignment statement immediately after End If. That assignment statement is outside the body of the If, so the true or false condition will not affect it. Therefore, the tax in the following routine executes regardless of whether the sales are more or less than $5000.00: If (Sales > 5000.00) Then Bonus = Sales * .12 curCostOfSales = Sales * .41 curReorderCost = Sales * .24 End If Tax = .15 * Sales The body of the If executes only if the comparison test is true. Otherwise, the rest of the program continues as usual. DPCDSB Computer Science TIK2O1 Page - 1 - LESSON 7 Visual Basic Selection (If Statements) THE IF STATEMENTS ELSE BRANCH Else specifies the code that executes if the comparison test is false. Here is the complete format of the If statement with Else: If comparisonTest Then 'One or more VB statements Else 'One or more VB statements End If The If-Else statement is sometimes called a mutually exclusive statement. The term mutually exclusive simply means that one set of code or the other executes, but not both. Suppose that a salesperson receives a bonus if sales are high (over $5,000.00) or suffers pay cut if sales are low (below $5,000.00). The If-Else shown next contains the code necessary to reward or punish the salesperson. The code body of the If computes the bonus as done in the previous section. The code body of the Else subtracts $25 from the salesperson's pay, which is stored in the variable named curPayAmt, if the sales quota is not met. The following code computes such a payment amount based on the quota: If (Sales > 5000.00) Then Bonus = .05 * Sales ‘Here we can count the number of Bonuses given Count = Count + 1 Else curPayAmt = curPayAmt – 25.00 End If curTaxes = curPayAmt * .42 Visual Basic takes everything to the right of the equal sign and stores that value in the variable to the left of the equal sign. Therefore, the fourth line subtracts the 25 from the value stored in curPayAmt and then assigns that result back to curPayAmt. In effect, it lowers the value of curPayAmt by 25. The Accumulator variable Count would have to be declared as Single and set to zero to begin the counter at zero. Example : DPCDSB Dim Count as Single Count = 0 Computer Science TIK2O1 Page - 2 - LESSON 7 Visual Basic Selection (If Statements) NESTED IF STATEMENTS The Nested If Statement is composed of many consecutive If Statements and forms a very detailed condition. The basic structure of the Nested If Statement is shown below. If condition then 'Body of Statement If condition then 'Body of Statement End If End If The order of the conditions is very important, as the program will proceed to the next condition only when one is found to be true. Otherwise, the program will proceed to the EndIf line that corresponds to that If Statement. ElseIf Statements can be incorporated into Nested If Statements. This construct is best for a number of related conditions If condition then 'Body of Statement ElseIf condition then 'Body of Statement ElseIf condition then 'Body of Statement else ‘Otherwise do these statement(s) End If DPCDSB Computer Science TIK2O1 Page - 3 - LESSON 7 Visual Basic Selection (If Statements) Assignment: Program Code / Error Detection Syntax Errors A statement that violates the rules of Visual Basic contains a syntax error. Most syntax errors are commonly just spelling (typo) mistakes. Example: Dim Months as Integer = 12 ‘Illegal in a variable declaration Some syntax errors, such as the one above, are immediately detected by Visual Basic, which displays the code in red. Other syntax errors may not be detected until you run the program. A run-time error is generated and a dialog box is displayed. Logic Errors Statements that are syntactically correct but produce unexpected results. Not just a spelling error or a rule violation but code which fails to generate the results desired. Circle the errors and note the type of error (logic & syntax) in the left column. Write the corrections in the right hand column Program A: Helping with the Food Drive Dim Answer as string ' Are you helping with the food drive? Answer = txtAnswer.Text Corrections if Answer = yes lblComment = "Thanks for the donation" end Program B: Old enough to drive Dim Age as Interger ' How old are you? Age = Val(txtAge.Text) Age >= 16 MsgBox "You are old enough to drive." Then MsgBox "You are not old enough to drive." end if Corrections Program C: Current mark Dim Mark is Byte Corrections 'What is your current mark is in this course? Mark = Val(txtMark.Text) if Mark >= 0 MsgBox "Much greater effort is needed." Else if mark >= 60 MsgBox "Satisfactory…need to improve" Else if Mark >=80 MsgBox "Keep up the Excellent work!" end if DPCDSB Computer Science TIK2O1 Page - 4 - LESSON 7 Visual Basic Selection (If Statements) Assignment: 1. Create a program, which would ask the question “What is the Capital of Canada? The program should allow the user to enter the answer. A Check Answer button will check to see if the answer is Ottawa. If the answer is not “Ottawa” then display Incorrect and if the answer is “Ottawa” then display Correct. 2. Write a program that asks the user to input the answer to the question "Should a keyboard be set at elbow or shoulder height?". If the input is elbow, output "Correct". Otherwise, output the correct answer along with an explanation. 3. Write a program to input two words and print these words in alphabetical order. GST (7%) is only applied when the number of muffins ordered is less than six. Therefore there is no GST on orders of six or more. Have the program display the GST amount as zero when the number of muffins are equal to or more than six. Include an image of a muffin (1” by 1”). Draw this picture or use a picture of a muffin found on the internet. Display the Final Bill in Currency format $##.## 4. Write a program which would allow the user to enter: the number of litres and the type of Gas purchased. The program is to calculate the Price of the Gas depending of the # of litres & type of Gas. User must be able to enter Gold, Silver, or Bronze for the Type of gas. Where the price of: Gold is $0.729, Silver is $0.709 and Bronze is $0.689. 5. Write a program to input three integers and output a message indicating their sum and whether it is positive, negative or zero. DPCDSB Computer Science TIK2O1 Page - 5 - LESSON 7 Visual Basic Selection (If Statements) 6. Create a program, which would ask five matching type questions. Each question is to have a picture of a Flag and a corresponding proposed country. The question is to be answered with a True (T) or False (F). A Check Answer button will check to see if the answers are correct. Comments are to indicate if the answer was correct or incorrect. A score is to be tallied of all the correct answers. The score is to be displayed. 7. Write a program, which would allow the user to enter their Annual Salary. The program is to display the Tax Bracket (maximum) Percentage and calculate the Total Income Tax According to the following table: Annual Salary Range $0 to $27500 $27501 to $55000 $55001 and up First 27500 Next 27500 Rest % 17% 24% 29% Example: Annual Salary = (First) 27500 * 17% = (Rest)10000 * 24% = TOTAL = $37500 $4675 $2400 $7075 Note that the entire amount was not multiplied by 24%, just the amount is that tax bracket. The program must also Exit when the option is chosen. DPCDSB Computer Science TIK2O1 Page - 6 - LESSON 7 Visual Basic Selection (If Statements) PROGRAMMING ASSIGNMENT RUBRIC /24 Criteria NAME: 1 2 3 4 Demonstrates limited ability to express a decision structure in a programming language. Demonstrates limited ability to write a program that compares data using constants, variables, and expressions. Demonstrates some ability to express a decision structure in a programming language. Demonstrates strong ability to express a decision structure in a programming language. Using a decision structure involving two or more alternatives SP3.06K Demonstrates limited ability to write a program that uses a decision structure involving two or more alternatives. Demonstrates some ability to write a program that uses a decision structure involving two or more alternatives. Using sequence and decisions appropriately SPV.04K SP3.08K Demonstrates limited ability to use appropriate sequences and decisions to conform to a program design. Demonstrates limited ability to document a decision structure. Demonstrates some ability to use appropriate sequences and decisions to conform to a program design. Demonstrates some ability to document a decision structure. Demonstrates considerable ability to express a decision structure in a programming language. Demonstrates considerable ability to write a program that compares data using constants, variables, and expressions. Demonstrates considerable ability to write a program that uses a decision structure involving two or more alternatives. Demonstrates considerable ability to use appropriate sequences and decisions to conform to a program design. Demonstrates considerable ability to document a decision structure. Demonstrates limited ability to validate a program using appropriate data. Demonstrates some ability to validate a program using appropriate data. Demonstrates considerable ability to validate a program using appropriate data. Demonstrates strong ability to validate a program using appropriate data. Expressing a decision structure SPV.04K TF3.04K Comparing data SP3.05K Documenting a decision structure SPV.03K SP3.09K Validating a program SP1.05K SP3.11K DPCDSB Demonstrates some ability to write a program that compares data using constants, variables, and expressions. Computer Science TIK2O1 Demonstrates strong ability to write a program that compares data using constants, variables, and expressions. Demonstrates strong ability to write a program that uses a decision structure involving two or more alternatives. Demonstrates strong ability to use appropriate sequences and decisions to conform to a program design. Demonstrates strong ability to document a decision structure. Page - 7 -