Private Sub btnWho_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWho.Click Dim intBob As Integer 'Bob's age Dim intJim As Integer 'Jim's age intBob = CInt(txtBob.Text) 'get user input intJim = CInt(txtJim.Text) txtOut.AppendText("Oldies are goodies." & vbCrLf) txtOut.AppendText("I like old people." & vbCrLf) If intBob > intJim Then 'Bob is oldest txtOut.AppendText("Bob is oldest." & vbCrLf) txtOut.AppendText("Bob is wiser." & vbCrLf) txtOut.AppendText("Jim is just a kid." & vbCrLf) Else 'Jim is oldest txtOut.AppendText("Jim is oldest." & vbCrLf) txtOut.AppendText("Jim is wiser." & vbCrLf) txtOut.AppendText("Bob is just a kid." & vbCrLf) End If txtOut.AppendText("That is how I see it." & vbCrLf) txtOut.AppendText("Do you agree?") End SubThe user enters Bob and Jim's ages into text boxes called txtBob and txtJim. If Bob is older, it displays three lines about how wise he is. If Bob is not older, it displays three lines about how wise Jim is.
The conditional statement in this example has three parts: If...Then, Else and End If. The syntax is:
If <Boolean expression> then one or more statements that are executed if the Boolean expression is true Else one or more statements that are executed if the Boolean expression is false End If When it comes to an If...Then...Else statement, the computer first evaluates the Boolean expression. If the expression is true, it executes the statements between If...Then and Else. In our example, that would mean it displays statements about Bob's being wise. If the expression is false, the computer executes the statements between Else and End If. In our example, that would mean it displays statements about Jim's being wise. Either way, the computer resumes sequential execution with the instruction just beyond the End If. This is illustrated in the flowchart on the right. Note that the flowchart is written in terms of the problem and in English, not in Basic. |