22/11/20151 2.1 Selection If selection construct.
-
Upload
maria-fletcher -
Category
Documents
-
view
233 -
download
1
Transcript of 22/11/20151 2.1 Selection If selection construct.
04/20/2304/20/23 11
2.1 Selection2.1 Selection
IfIf selection construct selection construct
2204/20/2304/20/23
Learning ObjectivesLearning Objectives
Describe the If structure and its variations.Describe the If structure and its variations.
Use and explain concatenation.Use and explain concatenation. Explain why we may want to join strings Explain why we may want to join strings
together and how we do it.together and how we do it.
Describe validation and explain how to do Describe validation and explain how to do it.it.
3304/20/2304/20/23
What is selection?What is selection?
A program testing whether a condition is A program testing whether a condition is true or false and - depending on the true or false and - depending on the answer - deciding to execute or not to answer - deciding to execute or not to execute one or more lines of code.execute one or more lines of code.
4404/20/2304/20/23
Types of Selection in VBTypes of Selection in VB
Two selection constructs:Two selection constructs: IfIf Select CaseSelect Case
5504/20/2304/20/23
The The IfIf construct has three construct has three variationsvariations
1.1. If ….. Then If ….. Then …..…..
End IfEnd If
2.2. If ….. Then If ….. Then ….. …..
ElseElse…..…..
End IfEnd If3.3. If ….. Then If ….. Then
….. ….. ElseIf …. ThenElseIf …. Then
……....ElseElse
…..…..End IfEnd If
6604/20/2304/20/23
Dim Age As IntegerDim Age As Integer
Age = Console.ReadLineAge = Console.ReadLine
If Age > 16 Then If Age > 16 Then ‘ Age greater than 16?‘ Age greater than 16? Console.WriteLine(“You are old enough to drive.”)Console.WriteLine(“You are old enough to drive.”)
End IfEnd If
1.1. If ….. Then If ….. Then …..…..End IfEnd If
7704/20/2304/20/23
NotesNotes
The condition to test is Age > 16. The condition to test is Age > 16. If it is true the message is shown, and if false the If it is true the message is shown, and if false the
message is skipped.message is skipped.
Because the condition is either true or false it is Because the condition is either true or false it is called a called a booleanboolean condition condition (Boolean is a data type)(Boolean is a data type)..
Any Any IfIf statement must always have a matching statement must always have a matching End IfEnd If to tell VB where the construct ends. to tell VB where the construct ends.
There are two routes through this example and There are two routes through this example and one condition to test.one condition to test.
8804/20/2304/20/23
Relational / Comparative OperatorsRelational / Comparative Operators
== equal toequal to
<< less thanless than
>> more thanmore than
<=<= smaller than or equal tosmaller than or equal to
>=>= greater than or equal togreater than or equal to
<><> not equal tonot equal to
These relational/comparative operators return value true or false to the program.
9904/20/2304/20/23
If Age > 16 Then If Age > 16 Then ‘ Age greater than 16?‘ Age greater than 16? Console.WriteLine(“You are old enough to Console.WriteLine(“You are old enough to
drive.”)drive.”)
Else Else ‘ Age 16 or less.‘ Age 16 or less. Console.WriteLine(“Sorry, you are too young to Console.WriteLine(“Sorry, you are too young to
drive. You must be 17 years old.”)drive. You must be 17 years old.”)
End IfEnd If
2.2. If ….. Then If ….. Then ….. ….. ElseElse…..…..End IfEnd If
101004/20/2304/20/23
NotesNotes
The The ElseElse part of the construct is executed part of the construct is executed if the boolean condition is false.if the boolean condition is false.
There are two routes through this example There are two routes through this example and one condition to test.and one condition to test.
111104/20/2304/20/23
3.3. If ….. Then If ….. Then ….. ….. ElseIfElseIf…..…..ElseElse…..…..End IfEnd If
121204/20/2304/20/23
If Age > 16 Then If Age > 16 Then ‘ Age greater than 16?‘ Age greater than 16? Console.WriteLine(“You are old enough to Console.WriteLine(“You are old enough to
drive.”)drive.”)
ElseIf Age = 16 Then ElseIf Age = 16 Then ‘ Age 16 exactly?‘ Age 16 exactly? Console.WriteLine(“Sorry, you are too young to Console.WriteLine(“Sorry, you are too young to
drive. You only have to wait less than a year drive. You only have to wait less than a year though.”)though.”)
Else Else ‘ Age 15 or less.‘ Age 15 or less. Console.WriteLine(“Sorry, you are too young to Console.WriteLine(“Sorry, you are too young to
drive. You must be 17 years old.”)drive. You must be 17 years old.”)
End IfEnd If
131304/20/2304/20/23
NotesNotes
There are three routes through this example There are three routes through this example and two boolean conditions to test.and two boolean conditions to test.For example:For example: If Age is 16:If Age is 16:
The first condition The first condition Age Age > 16 is false.> 16 is false.The second one, The second one, Age Age = 16, is tested, and since it is = 16, is tested, and since it is true the next two lines of code are executed.true the next two lines of code are executed.The Else part would be skipped.The Else part would be skipped.
More routes are possible if you use more More routes are possible if you use more ElseIf statements.ElseIf statements.
141404/20/2304/20/23
ConcatenationConcatenation
Joins strings together using the & Joins strings together using the & operator.operator. e.g. Putting a variable in a message:e.g. Putting a variable in a message:
Console.WriteLine(“My name is “ Console.WriteLine(“My name is “ && Name Name && “. I “. I am “ am “ && Age Age && “ years old.”) “ years old.”)
Will show Will show My name is …… I am … years old.My name is …… I am … years old.
151504/20/2304/20/23
Program 2.1a Program 2.1a Deciding exam gradesDeciding exam grades
SpecificationSpecification:: Ask the user to enter an exam mark from 0 to Ask the user to enter an exam mark from 0 to
100.100. Display the grade it represents – Merit (60 or Display the grade it represents – Merit (60 or
more), Pass (40 – 59), Fail (under 40).more), Pass (40 – 59), Fail (under 40).
161604/20/2304/20/23
Program 2.1aProgram 2.1aDeciding exam gradesDeciding exam grades
Dim Mark As IntegerDim Mark As IntegerConsole.WriteLine("Enter a mark.")Console.WriteLine("Enter a mark.")Mark = Console.ReadLineMark = Console.ReadLine‘‘The following If statement is after the declaring and storing lines The following If statement is after the declaring and storing lines because the Mark has to be stored before we can test it; it is before because the Mark has to be stored before we can test it; it is before the Message boxes because we have to decide which one to the Message boxes because we have to decide which one to display.display.If Mark >=60 Then If Mark >=60 Then ‘Mark 60 or more?‘Mark 60 or more?
Console.WriteLine(“Merit”)Console.WriteLine(“Merit”)ElseIf Mark >= 40 Then ElseIf Mark >= 40 Then ‘Mark 40 - 59?‘Mark 40 - 59?
Console.WriteLine(“Pass”)Console.WriteLine(“Pass”)Else Else ‘Mark under 40.‘Mark under 40.
Console.WriteLine(“A mark of “ & Mark & “ is a fail.”)Console.WriteLine(“A mark of “ & Mark & “ is a fail.”)End IfEnd If
171704/20/2304/20/23
Program 2.1a Program 2.1a Deciding exam gradesDeciding exam grades
Run the program and test each of the Run the program and test each of the three routes through the three routes through the IfIf construct by construct by entering the following marks:entering the following marks: 7070 5050 3030
181804/20/2304/20/23
ValidationValidation
Checking what the user enters obeys Checking what the user enters obeys predefined rules.predefined rules. e.g. enters numbers less than …. .e.g. enters numbers less than …. .
Validation: Checking for errors1
There are 2 ways to form IF constructs to check for errors: Simplistic Method:
If ErrorCheck is True Then Console.WriteLineConsole.WriteLine(“Suitable Error Message.”) ‘Show a suitable error message. Exit Sub ‘Stop the procedure.
End If
…..Code that you want executed if everything is OK.……
Without Without Exit SubExit Sub your your program will correctly program will correctly report the error but will report the error but will continue and crash continue and crash anyway. anyway.
Validation: Checking for errors2 More “professional” or “elegant” method:
If ErrorCheck is True Then Console.WriteLineConsole.WriteLine(“Suitable Error Message.”) ‘Show a suitable error message.
Else ….. Code that you want executed if everything is OK. ……
End If
If you have multiple error checks then just use a series of Else If’s for them, before the final Else.It doesn’t really matter which way you actually choose but you should attempt the more “elegant” method or at least be able to understand it, as this is the way it will probably be given to you in exams.
Commenting on If Statements
For presentations 2.1 – 2.4 I will only ask for comments to If statements.Your comments MUST explain:
What are you testing? Why are you testing for this? When (after and before what) are you testing for this
and why does it have to be there? What happens if the test is true?
Note that you may answer all these questions in one long comment either before or after the If statement you are commenting on; or you can answer each question with a separate comment. It is up to you.
Writing code which is easy to understand:Writing code which is easy to understand:
Sensible variable names.Sensible variable names.
Keywords in capitals.Keywords in capitals. So that the reader does not have to keep cross referencing with a table So that the reader does not have to keep cross referencing with a table
of variable names.of variable names.
Comments or Annotation.Comments or Annotation. To explain the logic of the code.To explain the logic of the code.
Indentation Indentation (this is done automatically by VB for you):(this is done automatically by VB for you):
To show the lines of the code that go together.To show the lines of the code that go together.For example:For example:
Private Sub butCalculateMean …Private Sub butCalculateMean …
Dim ….Dim ….
Mean = Total / NumberOfMarks Mean = Total / NumberOfMarks
lblMeanResult.Text = Mean.lblMeanResult.Text = Mean.
…….... End SubEnd Sub
2222
Given Pseudocode will use the following structure:
IF <condition>THEN
<statement(s)> ENDIF
or, including an ‘else’ clause:
IF <condition>THEN
<statement(s)>
ELSE <statement(s)>
ENDIF
Extension Program 2.1bDeciding Exam Grades
Extend the previous guided “2.1 Deciding exam grades” program so that it does not allow and shows suitable error messages if the mark entered is less than 0 or larger than 100.
Create a different error message for each situation:Mark entered is less than 0.
Mark entered is more than 100. Hint: test for these things first.
252504/20/2304/20/23
Extension “Salesman Bonus” Extension “Salesman Bonus” Program 2.1cProgram 2.1c
Write a program for a salesman to input the total Write a program for a salesman to input the total value of their sales this year and give their bonus:value of their sales this year and give their bonus: >= >= €100,000 then their bonus = €10,000.€100,000 then their bonus = €10,000. From €70,000 to €99,999.99 then their bonus = €7,000.From €70,000 to €99,999.99 then their bonus = €7,000. From €50,000 to €69,999.99 then their bonus = €4,000.From €50,000 to €69,999.99 then their bonus = €4,000. < then 50,000 then they receive no bonus.< then 50,000 then they receive no bonus.
Extension:Extension: What inputs should be disallowed here? Extend the program to do What inputs should be disallowed here? Extend the program to do
disallow these kind of inputs.disallow these kind of inputs.
Extension Income, Personal Allowance and Tax Rate Program 2.1d
Please extend program 1g from presentation “1 Variables/Identifiers” so that the program gives the right answer if a user enters a Salary less than the Personal Allowance.
Extension “/, DIV or MOD” Program Extension “/, DIV or MOD” Program 2.1e2.1e
Extend the “/, DIV or MOD” Program written in presentation 1 Variables/Identifiers so that it also calculates:
4. The number of actual boxes needed to pack all the melons (even if one is not full).
e.g. 2.5 boxes really means 3 boxes.
Extension Program “Cricket Match” 2.1fA program is to be written to enter and display the result of a cricket match. The winning team is the one scoring the most runs.The structured English description of the problem is shown here. It assumes the scores are not equal.
INPUT HomeTeamName INPUT HomeRuns INPUT AwayTeamName INPUT AwayRuns SUBTRACT AwaysRuns FROM HomeRuns STORE AS
RunDifference CALCULATE the winning team STORE AS WinningTeamName OUTPUT WinningTeamName and RunDifference
Typical output is shown.Write this program.
2929
Extension “Arithmetic Error” Program 2.1gExtension “Arithmetic Error” Program 2.1g
Write a program that will output the value of the Write a program that will output the value of the expression:expression:
Area /(SpaceWidth * SpaceLength – EmptySpaces)
What happens if the following values are used? SpaceWidth ← 7 SpaceLength ← 4 EmptySpaces ← 28
This is called an “arithmetic error”.Add code to stop this situation causing the program to crash.In your comments explain:
When (after or before what) did you check for the arithmetic error? Why did you check for it there? What you are checking for? What happens if your check is positive/true?
303004/20/2304/20/23
PlenaryPlenary
Why would we want to join strings together Why would we want to join strings together and how do we do it?and how do we do it? e.g. Putting a variable in a message:e.g. Putting a variable in a message:
Console.WriteLine(“My name is “ Console.WriteLine(“My name is “ && Name Name && “. I “. I am “ am “ && Age Age && “ years old.”) “ years old.”)
313104/20/2304/20/23
PlenaryPlenary
What does an What does an IfIf structure test? structure test? An If structure tests a boolean condition.An If structure tests a boolean condition.
What happens if this test returns What happens if this test returns TrueTrue?? If this test returns True then certain lines of code are If this test returns True then certain lines of code are
executed.executed.
What happens if this test returns What happens if this test returns FalseFalse (remember to mention the variations of the(remember to mention the variations of the IfIf structure)structure)?? Otherwise control passes to optional Otherwise control passes to optional ElseElse or or ElseIfElseIf
statements but ultimately the construct ends with an statements but ultimately the construct ends with an End If statement.End If statement.
323204/20/2304/20/23
PlenaryPlenary
What is validation, how is it done and how What is validation, how is it done and how do we stop errors like the program do we stop errors like the program attempting to store letters in a number attempting to store letters in a number variable?variable?
333304/20/2304/20/23
ValidationValidation
Checking what the user enters obeys Checking what the user enters obeys predefined rules.predefined rules. e.g. enters numbers less than …. .e.g. enters numbers less than …. .