Wednesday, January 15, 2014

In a program, a selection structure chooses among alternative courses of action. For exam-
ple,  suppose  that  the  passing  grade  on  an  examination  is  60  (out  of  100).  Then  the
pseudocode statement

       If student’s grade is greater than or equal to 60
               Print “Passed”

determines if the condition “student’s grade is greater than or equal to 60” is true or false.
If the condition is true, then Passed is printed, and the next pseudocode statement in order
is “performed.” (Remember that pseudocode is not a real programming language.) If the
condition is false, the print statement is ignored, and the next pseudocode statement in order
is performed. Note that the second line of this selection structure is indented. Such inden-
tation is optional, but it is highly recommended because it emphasizes the inherent structure

of structured programs. The preceding pseudocode If statement may be written in C# as

        if ( studentGrade >= 60 ) 
        Console.WriteLine( "Passed" );

Notice  that  the  C#  code  corresponds  closely  to  the  pseudocode,  demonstrating  how
pseudocode can be useful as a program development tool. The statement in the body of the

if structure outputs the character string "Passed" in the console window.

The flowchart in Fig. 4.3 illustrates the single-selection if structure. This flowchart
contains  the  most  important  flowcharting  symbol—the  decision  (or  diamond)  symbol,
which indicates that a decision is to be made. The decision symbol contains a condition,
that can be either true or false. The decision symbol has two flowlines emerging from
it. One indicates the direction to be taken when the condition in the symbol is true; the other
indicates the direction to be taken when the condition is false. A decision can be made on
any expression that evaluates to a value of C#’s bool type (i.e., any expression that eval-
uates to true or false).

Note that the if structure, too, is a single-entry/single-exit structure. The flowcharts
for the remaining control structures also contain (aside from small circle symbols and flow-
lines) only rectangle symbols, to indicate the actions to be performed, and diamond sym-
bols, to indicate decisions to be made. This is the action/decision model of programming
we have been emphasizing.

We can envision eight bins, each containing control structures for only one of the eight
types. The control structures in each bin are empty; nothing is written in the rectangles or dia-
monds. The programmer’s task is to assemble a program using as many control structures as
the  algorithm  demands,  combining  those  control  structures  in  only  two  possible  ways
(stacking or nesting), then filling in the actions and decisions in a manner appropriate for the
algorithm. We will discuss the variety of ways in which actions and decisions may be written.

0 comments:

Post a Comment

Subscribe to RSS Feed Follow me on Twitter!