conditional statements
TRANSCRIPT
CONDITIONAL STATEMENT
Conditions are logical expressions that evaluate to a True/False value and they usually contain comparison
operators— equals (=), different (<>), less than (<), greater than (>), less than or equal to (<=), and so on — and logical operators: And, Or, X or, and Not. Here are a few examples
of valid conditions:
If (age1 < age2) And (age1 > 12) Then ...
If score1 = score2 Then ...
FORMS OF IF STATEMENT
1. if … statement then 1 condition
2. if … statement has Else part
3. if statement has one or more Else if parts
If … then statement
The If. . .Then statement tests an expression, which is known as a condition. If the condition is True, the program executes the statement(s) that follow.
The If. . .Then statement can have a single-line or a multiple-line syntax. To execute one statement conditionally, use the single-line syntax as follows:
If condition Then statement is TRUE
End if
Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "Hello!" Then Label1.Text = "World" End Sub
Another example:
Dim a As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
a = TextBox1.Text If a >= 18 Then label1.text ("You can now vote online.")End Sub
2. if … statement has Else part
If the condition is evaluates correct, then the statement are executed.
If the condition is evaluates false, then thestatements are executed.
Syntax:If condition Then
statement is TrueElse
statement is FalseEnd if
Dim a As IntegerPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
a = TextBox1.TextIf a >= 18 Then Label1.Text = "You can now
vote online." Else Label1.Text = "You can not vote“
End Sub
Another Example: (Using Boolean/Logical Operation)
If TextBox1.Text = “Apple" And / Or TextBox2.Text = “Banana"
Then Label1.Text = "Fruit“ Else Label1.Text = “Junk Food"
3. if statement has one or more Elseif parts
One or more statements and condition.
Syntax:
If Condition1 thenstatements to be if condition is trueElse if condition2 thenstatements to be executed is False but Condition2 is TrueElse if condition3 thenstatements to be executed if Con1 and Con2 are False but Condition3 is TrueElse statements to be executed if all of the above conditions are False.End Sub
Dim Grade as IntegerGrade = txtgrade.Text If Grade <= 74 Then MsgBox("You Failed!") Else If Grade <= 80 Then MsgBox("Needs Improvement!") Else If Grade <= 85 Then MsgBox("Average!") Else If Grade <= 90 Then MsgBox("Satisfactory!") Else If Grade <= 95 Then MsgBox("Very Satisfactory!") Else MsgBox("Excellent!")End Sub
Note:
Aside from Message box, you may also use the controls such as label and textbox, if you
want to show the executed statements or condition.