Section 5.3. If...Then Selection Statement


5.3. If...Then Selection Statement

A selection statement chooses among alternative courses of action. For example, suppose that the passing grade on an examination is 60 (out of 100). Then the statement

 If studentGrade >= 60 Then    Console.WriteLine ("Passed") End If 


outputs the string "Passed" if the student's grade is at least 60.

The preceding If...Then selection statement also could be written on a single line as

 If studentGrade >= 60 Then Console.WriteLine("Passed" 


In the multiple-line format, all statements (there can be many) in the body of the If...Then are executed if the condition is true. In the single-line format, only the statement immediately after the Then keyword is executed if the condition is true. Although writing the If...Then selection statement in the latter format saves space, some programmers feel that the organization of the statement is clearer when the multiple-line format is used.

Figure 5.2 is an activity diagram that illustrates the single-selection If...Then statement. It contains what is perhaps the most important symbol in an activity diagramthe diamond, or decision symbol, which indicates that a decision is to be made. A decision symbol indicates that the workflow will continue along a path determined by the symbol's associated guard conditions, which can be true or false. Each transition arrow emerging from a decision symbol has a guard condition (specified in square brackets above or next to the transition arrow). If a particular guard condition is true, the workflow enters the action state to which that transition arrow points. Exactly one of the guard conditions associated with a decision symbol must be true when a decision is made. In Fig. 5.2, if the grade is greater than or equal to 60, the program prints "Passed" to the screen, then transitions to the final state of this activity. If the grade is less than 60, the program immediately transitions to the final state without displaying a message.

Figure 5.2. If...Then singleselection statement activity diagram.


Note that the If...Then statement is a single-entry/single-exit statement (as are all Visual Basic control statements). The activity diagrams for the remaining control statements also contain initial states, transition arrows, action states that indicate actions to perform, decision symbols (with associated guard conditions) that indicate decisions to be made, and final states.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net