5.4. If...Then...Else Selection StatementAs we have explained, the If...Then selection statement performs an indicated action (or sequence of actions) only when the condition evaluates to true; otherwise, the action (or sequence of actions) is skipped. The If...Then...Else selection statement allows you to specify that a different action (or sequence of actions) is to be performed when the condition is true than when the condition is false. For example, the Visual Basic statement If studentGrade >= 60 Then Console.WriteLine("Passed") Else Console.WriteLine("Failed" End If prints "Passed" if the student's grade is greater than or equal to 60, and prints "Failed" if the student's grade is less than 60. In either case, after printing occurs, the next statement in sequence executes. Figure 5.3 illustrates the flow of control in the If...Then...Else statement. Once again, note that (besides the initial state, transition arrows and final state) the only other symbols in this activity diagram represent action states and decisions. Figure 5.3. If... Then... Else doubleselection statement activity diagram.Nested If...Then...Else StatementsNested If...Then...Else statements test for multiple conditions by placing If...Then...Else statements inside other If...Then...Else statements. For example, the following statement will print "A" for exam grades greater than or equal to 90, "B" for grades in the range 8089, "C" for grades in the range 7079, "D" for grades in the range 6069 and "F" for all other grades. If studentGrade >= 90 Then Console.WriteLine("A") Else If studentGrade >= 80 Then Console.WriteLine("B") Else If studentGrade >= 70 Then Console.WriteLine("C") Else If studentGrade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If End If End If End If If studentGrade is greater than or equal to 90, the first four conditions are true, but only the Console.WriteLine statement in the body of the first test is executed. After that particular Console.WriteLine executes, the Else part of the "outer" If...Then...Else statement is skipped, and the program proceeds with the next statement after the last End If. Good Programming Practice 5.1
Some Visual Basic programmers prefer to write the preceding If...Then...Else statement using the ElseIf keyword as If grade >= 90 Then Console.WriteLine("A") ElseIf grade >= 80 Then Console.WriteLine("B") ElseIf grade >= 70 Then Console.WriteLine("C") ElseIf grade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If Both forms are equivalent, but the latter is popular because it avoids the deep indentation of the code. Such deep indentation often leaves little room on a line, forcing lines to be split and decreasing program readability. |