Visual Basic 2005 for Programmers (2nd Edition)
3.7. Decision Making: Equality and Relational Operators
This section introduces Visual Basic's If...Then statement, which allows a program to make a decision based on the truth or falsity of some expression. The expression in an If...Then statement is called a condition. If the condition is met (i.e., the condition is true), the statement in the If...Then statement's body executes. If the condition is not met (i.e., the condition is false), the body statement is not executed. Conditions in If...Then statements can be formed by using the equality operators and relational operators (also called comparison operators), which are summarized in Fig. 3.21. The relational and equality operators all have the same level of precedence and associate from left to right.
Common Programming Error 3.3
The next example uses six If...Then statements to compare two numbers entered into a program by the user. If the condition in any of these statements is true, the output statement associated with that If...Then executes. The user enters these values, which are stored in variables number1 and number2, respectively. The comparisons are performed, and the results of the comparison are displayed in the Console window. The program and outputs are shown in Fig. 3.22. Figure 3.22. Performing comparisons with equality and relational operators.
The If...Then statement in lines 2022 compares the values of the variables number1 and number2 for equality. If the values are equal, the statement in line 21 outputs a string indicating that the two numbers are equal. Note that assignment and the equality operator both use the = symbol. When a condition is expected (such as after the If keyword in an If...Else statement), the = is used as an equality operator. If number1 contains the value 333 and number2 contains the value 333, the expression in line 21 evaluates as follows: number1 is converted to a string and concatenated with the string "=", then number2 is converted to a string and concatenated with the resulting string from the first concatenation. At this point, the string "333 = 333" is displayed by WriteLine. As the program proceeds through the remaining If...Then statements (lines 2444), additional strings are output by the WriteLine statements. For example, when given the value 333 for number1 and number2, the conditions in lines 37 and 42 also are true. Thus, the output displayed (in the third output of Fig. 3.22) is: 333 = 333 333 <= 333 333 >= 333 The table in Fig. 3.23 shows the precedence of the operators introduced in this chapter. The operators are displayed from top to bottom in decreasing order of precedence.
|