If….Then Statement

UNIT 4
Lesson 13
If statements
•
If…Then…Else control structure
We shall learn how to write code that can make
decisions and control the program flow.
•
Decision making process is an integral part of
programming. The ability to make decision helps solve
problems intelligently and provide useful output to the
user.
•
For example, we can write a program that can ask the
computer to perform certain task until a certain condition
is met, or a program that will reject non-numeric data. In
order to control the program flow and to make decisions,
we need to use the conditional operators and the logical
operators together with the If…Then…Else control
structure.
Conditional Operators
• The conditional operators are powerful tools that
resemble mathematical operators.
• These operators allow a program to compare data
values and then decide what actions to take, whether
to execute a program or terminate the program. They
are also known as numerical comparison operators.
• They are used to compare two values to see whether
they are equal, one value is greater or less than the
other value.
•
The comparison will return a true or false result.
Relational Operators
OPERATOR
DESCRIPTION
=
Equal to
>
Greater than
<
Less than
>=
Equal to or Greater than
<=
<>
Less than or Equal to
Not equal to
Logical Operators
Sometimes we might need to make more than one comparison before a decision
can be made and an action taken. In this case, using numerical comparison
operators alone is not sufficient, we need to use additional operators, and they
are the logical operators.
OPERATOR
And
DESCRIPTION
Both sides must be true
Or
One side or other must be true
Xor
One side or other must be true but not both
Not
Negates true
The above operators can be used to compare numerical data as well as non-numeric
data such as text(string). In making strings comparison, there are certain rules to
follows: Upper case letters are less than lowercase letters, “A”<”B”<”C”<”D”…….<”Z”
and number are less than letters.
Using the If control structure
with the Comparison Operators
• To effectively control the program flow, we
shall use the If control structure together
with the conditional operators and logical
operators.
• There are basically three types of If control
structures, namely
If….Then statement,
If…Then…Else statement
If…Then…ElseIf statement.
If….Then Statement
This is the simplest control structure which instructs the computer to perform a
certain action specified by the expression if the condition is true. However, when
the condition is false, no action will be performed. The syntax for the if…then
statement is
If condition Then
Visual Basic 2013 expressions
End If
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim intMyNumber As Integer
intMyNumber = txtInput.Text
If intMyNumber > 100 Then
lblDisplay.Text = ” You win a lucky prize”
End If
End Sub
* When you run the program and enter a number that is greater than 100, you will
see the “You win a lucky prize” statement. On the other hand, if the number entered
is less than or equal to 100, you don’t see any display.
If…Then…Else Statement
Using just If….Then statement is not very useful in programming and it does not provide
choices for the users. In order to provide a choice, we can use the If….Then…Else Statement.
This control structure will ask the computer to perform a certain action specified by the Visual
Basic 2013 expression if the condition is met. And when the condition is false, an alternative
action will be executed. The syntax for the if…then.. Else statement is
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim intMyNumber As Integer
intMyNumber = txtInput.Text
If intMyNumber > 100 Then
lblDisplay.Text = ” Congratulation! You win a lucky prize”
Else
lblDisplay.Text = ” Sorry, You did not win any prize”
End If
End Sub
* When you run the program and enter a number that is greater than 100, the statement
“Congratulation! You win a lucky prize” will be shown. On the other hand, if the number
entered is less than or equal to 100, you will see the “Sorry, You did not win any prize”
statement
Example
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim intMyNumber, intMyAge As Integer
intMyNumber = txtNum.Text
myAge = txtAge.Text
If intMyNumber > 100 And intMyAge > 60 Then
lblDisplay.Text = “Congratulation! You win a lucky prize”
Else
lblDisplay.Text = “Sorry, You did not win any prize”
End If
End Sub
* This program use the logical operator And beside the conditional
operators. This means that both the conditions must be fulfilled in order for
the conditions to be true, otherwise the second block of code will be
executed. In this example, the number entered must be more than 100 and
the age must be more than 60 in order to win a lucky prize, any one of the
above conditions not fulfilled will disqualify the user from winning a prize.
The If…Then Statement
• If…Then statement is a decision structure that
executes code when a condition is true.
– Example:
If intGuess = 10 Then
lblGuessCheckedMessage.Text = “You guessed
it!”
End If
If the value of intGuess is 10, the Text property of the
label object is executed.
If the value of intGuess in not equal to 10, then the
assignment statement is not executed and program
flow continue on to the next line after the End If.
You can have multiple lines of code between the Then
and End If
Equal Symbol (=)
Has two purposes:
Comparison – compare two values and return
true or false. (If Statements)
Assignment – Takes the value on the right side
and set the left side memory location to the
value.
Boolean Expression & Relational Operators
• The condition of the If condition Then statement
is a Boolean expression.
• Boolean expression – evaluates to either True or
False.
• A Boolean variable may also be used as the
condition of the If…Then statement.
– Example: Dim blnAns As Boolean
blnAns = True
If blnAns Then
Some type of code goes here
End If
Relational Operators
Six relational operators:






= equal sign
< less than
<= less than or equal to
> Greater than
>= Greater than or equal to
<> Not equal to
Roundoff Error
 If…Then statement should never make an
equality (=) comparison between floating
point numbers (numbers with decimals)
because of the possibility of a roundoff
error.
The If…Then…Else Statement
 Optional to an If…Then statement
 Executed when the If condition evaluates to False.
 If…Then…Else form:
If condition Then
statement
Else
statement
End If
Example of an If…Then…Else
Statement
Private Sub cmdCheckGuess_Click()
Const intNum As Integer = 10
Dim intGuess As Integer
intGuess = txtGuess.Text
If intGuess = intNum Then
lblGuessMessage.Text= “You guessed it”
Else
lblGuessMessage.Text = “Try again”
End If
End Sub
Typing a number other than 10 will display “Try again”
Indentation
• Indentation helps readability
• Indentation has no effect on the execution of the statement.
• For an If…Then…Else all executable code inside the
statement should be indented.
Example:
If condition Then
executable code
Else
executable code
End If
Nested If…Then…Else
Statements
Nested If…Then…Else
• Nested If…Then…Else Statement - is an If
statement inside another If statement or an
Else statement.
• There are many combinations that you can
use with nested If statements that you can
not cover all of them.
Examples
If Boolean Condition Then
Code1 Statement
If Boolean Condition Then
Code2 Statement
statement
End If
Else
Code3 Statement
End If
‘ nested if
Example Continued
• If intGuess = intSecretNumber Then
lblGuessCheckedMessage.text = “you guessed it!
Else
If intGuess < intSecretNumber Then
lblGuessCheckedMessage.text = “too low”
Else
lblGuessCheckedMessage.text = “too high”
End If
End If
(nested statements should be indented for good programming
style)
Examples
If condition1 Then
Code1
Else
If condition2 Then
Code2
Else
Code3
End If
End If
When conditional1 is false, the else
portion will run and check condition2.
If codition2 is false then Code3 will run.
If condition1 is true, Code1 will run and
everything else is skipped. If condition1 is
false and condition2 is true then
Code2 will run.
Example
If condition1 Then
If condition2 Then
If condition3 Then
Code1
Else
Code2
End If
Else
Code3
End If
Else
Code4
End If
The If…Then…ElseIf Statement
• Is used to decide among three or more actions
where only the first If or ElseIf condition that
is true runs and all others are skipped.
• Notice there is no space in the ElseIf
• An ElseIf can contain an If statement
• The Else statement is optional
Example
If condition1 Then
Code1
ElseIf condition2 Then
Code2
ElseIf condition3 Then
Code3
ElseIf condition4 Then
Code4
Else
Code5
End If
Example Continued (ElseIf)
• Used to decide among 3, 4, or more actions
• This example includes three possible decisions in the
IF..Then…ElseIf:
If intGuess = intSecretNumber Then
lblGuessCheckedMessage.text= “you guessed it”
ElseIf intGuess < intSecretNumber Then
lblGuessedCheckedMessage.text=“too low”
Else
lblGuessCheckedMessage.text= “too high”
End If
Programming Style
• The use of If…Then… ElseIf is better and
easier to read then the nested If…Then…Else
• Beware of the range of the conditions in an
If…Then…ElseIf because the first condition
that evaluates true will run and then the rest
of the ElseIf statements are skipped.
Generating Random Numbers
Generating Random Numbers
• Built-in function – Built-in meaning that Visual
Basic already has it and it doesn’t need to be
coded.
• Rnd function – generates a random number
greater than or equal to 0 and less than 1.
Functions
• Visual Basic has many built-in functions.
• Function – is a procedure that performs a
task and returns a value.
• Predefined functions are used by including
the function name in a statement.
• When the line of code containing the function
name is executed, the statements that make
up the function are executed.
Function Arguments
• Arguments are data that functions requires to
perform its task.
• The data is “passed” to the function as arguments
enclosed in parentheses after the function name.
– Example: Int(-5.4) which will return –6.
RND function
 Using Rnd alone generates random numbers
greater than or equal to 0 and less than 1.
 If you want to generate numbers in a greater
range, simply multiply Rnd by the upper
number of the range you want.
◦ Example: lblRanNum.Text = Rnd * 10
 Generate numbers in a range with an upper and
lower limt do the following.
◦ (HighNumber – LowNumber + 1) * Rnd +
LowNumber
◦ Where HighNumber and LowNumber represents the
limits of the range.
Int function
• Returns the Integer portion of a number
without rounding.
– Example: Int(21 * Rnd + 10) ‘will return the
integer portion only
Again,
This number is found by using the equation
(HighNumber-LowNumber + 1) * Rnd +LowNumber
Fix Function
• Very similar to the Int function
• Both will work the same for positive numbers by
returning the Integer portion only.
• Negative numbers Integer function returns the
Integer less than or equal to its negative argument.
• Fix Function returns the first integer greater than
or equal to its negative argument
– Example: Fix(-5.4) would return –5.
– Int(-5.4) would return –6.
Randomize
• Programs that uses Rnd function should include
a Randomize statement.
• The Randomize statement initializes the Visual
Basic Rnd function so different random numbers
are generated in a program from run to run.
• Best place for the Randomize statement is in the
Form_Load() procedure because it occurs only
once.
– Example: Private Sub Form_Load()
Randomize
End Sub
How Random Numbers are
Generated
• Uses the computer’s clock to generate a
seed value.
• A seed is a value used by the Rnd function
to generate a pseudorandom (not truly
random) sequence of numbers.
• Each time the Rnd is used, the next
number in the sequence is returned.
Scope
• Scope of a variable or constant – refers to its
accessibility among procedures. Is where the
variable or constant can be accessed or used.
– Example: the scope of a variable declared in an event
procedure is limited to that procedure. No other
procedure can refer to that variable or change its value.
– Variables declared in procedures are considered “local”
variables of that procedure.
Global Variables
• Global variables declared in the General section
of a form module are accessible to every
procedure. This is known as “Global” variables.
• Global variable declaration should use the
keyword Private in place of the keyword Dim.
• Global Constants declarations should use the
keyword Private in front of the keyword Const.
• Global variables are declared right after the
Option Explicit statement outside of any
procedures.
Programming Style
• Local variables should be used whenever possible
because they don’t interfere with other procedures.
• Two procedures can contain the same variable
names and each has their own values.
• Global variables that are not declared as constant
can cause debugging problems because any
procedure can change the global variable value.
You can do it without a constant but you must
make sure errors do not occur—Check Code
Logical Operators
• 4 types of logical operators
–
–
–
–
And
Or
Not
Xor
• A logical operator joins two expressions to create an
expression that evaluates to either true or false
– Example: dblnum > 0 And dblnum <= 10 will evaluate to
true if dblNum is in the range 0<dblnum<=10. It would
evaluate false otherwise.
And
•
•
•
•
•
Expression1 And Expression2
True And True = True
False And True = False
True And False = False
False And False = False
– So the only time an And operator evaluates to
true is when both expressions are true.
Or
•
•
•
•
•
Expression1 Or Expression2
True Or True = True
False Or True = True
True Or False = True
False Or False = False
– So if one or both expressions evaluates to true
than it equals true. The only time it evaluates to
false if both expressions are false.
Not
• Expression Result
• Not True
False
• Not False
True
– Note that the Not changes it to the opposite.
Xor
•
•
•
•
•
Expression1 Or Expression2
True Or True = False
False Or True = True
True Or False = True
False Or False = False
Operator Precedence
•
•
•
•
•
Not is evaluated before an And
An And is evaluated before an Or
Or is evaluated before Xor
Xor is last
You can use parentheses to change the order.
Algorithms
• Algorithm – is a series of steps that tell how
to solve a problem.
• Pseudocode – half English and half code of
instructions to solve a problem.
• Flow Chart – use of symbols to show the
flow of code.
Errors
• Compile Error –Syntax Errors
• Run Time errors – occurs at runtime.
Dividing a variable by zero.
• Logic errors – programs runs but the
output is incorrect. Usually bad formula.
If…Then…ElseIf Statement
If there are more than two alternative choices, using just If…Then…Else
statement will not be enough. In order to provide more choices, we can
use the If….Then…ElseIf Statement. The general structure for the if…then..
Elseif statement is
If condition Then
Visual Basic 2013 expression
ElseIf condition Then
Visual Basic 2013 expression
ElseIf condition Then
Visual Basic 2013 expression
.
.
Else
Visual Basic 2013 expression
End If
Example
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim intMark As Integer
Dim strGrade as String
intMark = txtInput.Text
If intMark >=80 Then
Grade = “A”
ElseIf Mark >= 60 And Mark < 80
Grade= “B”
ElseIf Mark >= 40 And Mark < 60
Grade = “C”
Else
Grade = “D”
End If
End Sub
UNIT 4
Lesson 14
Select Case Statement
Select Case Control Structure
• The Select Case control structure is slightly different
from the If….then…Else control structure.
• The difference is that the Select Case control
structure basically only makes decision on one
expression or dimension.
• On the other hand, the If…Then…Else statement
may evaluate only one expression, each If statement
may also compute entirely different dimensions.
• Select Case is preferred when there exist multiple
conditions as using If…Then..ElseIf statements will
become too complicated.
The Select Case…End Select Structure
The structure of the Select Case control structure in is as
follows:
Select Case test expression
Case expression list 1
Block of one or more Visual Basic 2013 statements
Case expression list 2
Block of one or more Visual Basic 2013 Statements
Case expression list 3
.
.
Case Else
Block of one or more Visual Basic 2013 Statements
End Select
The usage of Select Case examples
Example: Examination Grades
Private Sub Compute_Click( )
Dim strGrade As String
strGrade = txtgrade.Text
Select Case strGrade
Case “A”
lblDisplay.Text=”High Distinction”
Case “A-”
lblDisplay.Text=”Distinction”
Case “B”
lblDisplay.Text=”Credit”
Case “C”
lblDisplay.Text=”Pass”
Case Else
lblDisplay.Text=”Fail”
End Select
Example
In this example, you can use the keyword Is together with the comparison
operators.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dblMark As Double
dblMark = txtMrk.Text
Select Case strMark
’Examination Marks
Case Is >= 85
lblDisplay.Text= “Excellence”
Case Is >= 70
lblDisplay.Text= “Good”
Case Is >= 60
lblDisplay.Text = “Above Average”
Case Is >= 50
lblDisplay.Text= “Average”
Case Else
lblDisplay.Text = “Need to work harder”
End Select
End Sub
Example
Rewritten as follows:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dblMark As Double
dblMark = txtInput.Text
Select Case dblMark
‘Examination Marks
Case 0 to 49
lblDisplay.Text = “Need to work harder”
Case 50 to 59
lblDisplay.Text = “Average” s
Case 60 to 69
lblDisplay.Text= “Above Average”
Case 70 to 84
lblDisplay.Text = “Good”
Case 85 to 100
lblDisplay.Text= “Excellence”
Case Else
lblDisplay.Text= “Wrong entry, please reenter the mark”
End Select
End Sub
Example
Grades in high school are usually presented with a single capital letter such as A, B, C, D or E.
The grades can be computed as follow:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dblMark As Double
dblMark = txtInput.Text
Select Case dblMark
‘Examination Marks
Case 0 To 49
lblDisplay.Text = “E”
Case 50 To 59
lblDisplay.Text = “D”
Case 60 To 69
lblDisplay.Text = “C”
Case 70 To 79
lblDisplay.Text = “B”
Case 80 To 100
lblDisplay.Text = “A”
Case Else
lblDisplay.Text = “Error, please reenter the mark”
End Select
End Sub
Errors
•
Roundoff Errors
• The condition of an If – Then statement should never make an
equality comparison between floating points (numbers with
decimals) because of the possibility of roundoff error.
• Roundoff Error – occurs because floating point numbers cannot
be exactly represented in binary notation by the computer.
Example: Repeating decimals
Logical Errors
• Logical Errors are program that are syntactically correct but
produces the wrong answer. Logical errors are usually because of
a math error or bad formula.
Programming Style
• Proper indentation of code is necessary for
readability. All statements of an If – Then
structure should be indented.
Generating Random Numbers
•
Many programs especially games require a way to generating random numbers.
In VB, we use the built-in Rnd function to generate numbers between 0 and less
than 1 (not including 1).
•
What are functions? – In VB, there are many built-in functions. A function is a
type of procedure that performs a task and returns a value. A line of code will
have the function name in it and when the program reaches the built-in
function, the program will run the function and return the value in place of the
function name.
•
What are function arguments? Arguments is a way to pass a value to a function
and have the function use the value to generate a new value that is returned to
the function call in the statement.
•
To use the Rnd function, you must type in the Randomize statement in the
form_load procedure. Though it could be type in other procedure, it is better in
the form_load procedure because it automatically runs when the user starts the
program.
Example:
Private Sub Form_Load()
Randomize
End Sub
Rnd function Examples:
LblDisplay.text = Rnd * 10 ‘ Generates random numbers between 0
and less than 10
To generate a number in a range use the following formula.
(High Number – Low Number + 1) * Rnd + Low Number
Example: Generate numbers greater than or equal to 10 and less
than 31
Use the following expression (30 – 10 + 1) * Rnd + 10
Int & Fix Functions
Int Function - returns the integer portion of a number
without rounding.
Example: Int((30 – 10 + 1 ) * Rnd + 10) ‘ returns an Integer
portion only
Fix Function – very similar to the Int function accepts for
negative numbers. When working with negative numbers,
the Int function will returns the first negative integer less
than or equal to its argument (number inside the
parentheses), while the Fix returns the first negative integer
that is greater than or equal to its argument.
Examples:
Int(-5.4) -> -6
Fix(-5.4) -> -5