Saturday, March 22, 2014

A repetition structure allows the programmer to specify that an action is to be repeated
while a condition remains true. The pseudocode statement

While there are more items on my shopping list
Purchase next item and cross it off my list

describes the repetition that occurs during a shopping trip. The condition, “there are more items on my shopping list” may be true or false. If it is true, then the action, “Purchase next item and cross it off my list” is performed. This action executes repeatedly while the condition remains true. The statement(s) contained in the while repetition structure constitute the body of the while. The while structure body may be a single statement or a block. Eventually, the condition becomes false (when the last item on the shopping list has been purchased  and  crossed  off  the  list).  At  this  point,  the  repetition  terminates,  and  the  first statement after the repetition structure executes.

As an example of a while structure, consider a program segment designed to find the
first power of 2 larger than 1000. Suppose int variable product contains the value 2.
When the following while structure finishes executing, product contains the result:

      int product = 2;
     while ( product <= 1000 )
      product = 2 * product;


The flowchart in Fig. 4.5 illustrates the flow of control of the preceding while repetition structure. Once again, note that (besides small circles and arrows) the flowchart contains only a rectangle symbol and a diamond symbol.

Common Programming Error 4.3
Not providing in the body of a while structure an action that eventually causes the condition to become false is a logic error. Normally, such a repetition structure will never terminate, which is an error called an “infinite loop.”                                                              
Common Programming Error 4.4
Beginning the keyword while with an uppercase W, as in While, is a syntax error. Remember that C# is a case-sensitive
language. All of C#’s keywords—while, if, else, etc.contain only lowercase letters.     

image 

Testing and Debugging Tip 4.2
Visual Studio .NET will not color a keyword properly unless that keyword is spelled correctly and with the correct case.
                

        Imagine, again, a deep bin of empty while structures that may be stacked and nested with other control structures to form a structured implementation of an algorithm’s flow of control. The empty rectangles and diamonds are filled with appropriate actions and decisions. The flowchart clearly shows the repetition. The flowline emerging from the rectangle indicates that program control continues with the decision, which is tested during each iteration of the loop until the decision eventually becomes false. At this point, the while structure terminates, and control passes to the next statement following the while structure in the program.
 

         When the while structure begins executing, product is 2. Variable product is
repeatedly multiplied by 2, taking on the values 4, 8, 16, 32, 64, 128, 256, 512 and 1024,successively. When  product becomes 1024, the condition  product <= 1000 in the while structure becomes false. This terminates the repetition with 1024 as product’s final value. Execution continues with the next statement after the while. [Note: If a while structure’s condition is initially false, the body statement(s) will never be executed.]

Wednesday, January 15, 2014

The if selection structure performs an indicated action only when the condition evaluates
to true; otherwise, the action is skipped. The if/else selection structure allows the pro-
grammer to specify different actions to perform when the condition is true and when the
condition is false. For example, the pseudocode statement

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


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 pseudocode

statement in sequence is “performed.”

         The preceding pseudocode If/Else structure may be written in C# as

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

 

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.
Normally, statements in a program execute one after the other in the order in which they
appear in the program. This is called sequential execution. Various C# statements enable
the programmer to specify that the next statement to execute may not be the next one in
sequence. A transfer of control occurs when a statement other than the next one in the pro-
gram executes.

During the 1960s, it became clear that the indiscriminate use of transfers of control was
causing difficulty for software development groups. The problem was the goto statement,
which, in some programming languages, allows the programmer to specify a transfer of
control to one of a wide range of possible destinations in a program. This caused programs
to become quite unstructured and hard to follow. The notion of structured programming
became almost synonymous with “goto elimination.”

The research of Bohm and Jacopini1 demonstrated that all programs with goto state-
ments could be written without them. The challenge of the era for programmers was to shift
their  styles  to  “goto-less  programming.”  It  was  not  until  the  1970s  that  programmers
started taking structured programming seriously. The results were impressive, as software
development groups reported reduced development times, more frequent on-time delivery
of systems and more frequent within-budget completion of software projects. The key to
these successes was that structured programs were clearer, easier to debug and modify and
more likely to be bug-free in the first place.

Bohm and Jacopini’s work demonstrated that all programs could be written in terms of
only three control structures, namely, the sequence structure, the selection structure and
the repetition structure. The sequence structure is built into C#. Unless directed otherwise,
the computer executes C# statements one after the other in the order in which they appear
in a program. The flowchart segment of Fig. 4.1 illustrates a typical sequence structure in
which two calculations are performed in order.

A flowchart is a graphical representation of an algorithm or of a portion of an algo-
rithm. Flowcharts contain certain special-purpose symbols, such as rectangles, diamonds,
ovals and small circles. These symbols are connected by arrows called flowlines, which
indicate the order in which the actions of the algorithm execute. This order is known as the
flow of control.

Like pseudocode, flowcharts often are useful for developing and representing algo-
rithms, although pseudocode is preferred by many programmers. Flowcharts show clearly
how control structures operate; that is all we use them for in this text. The reader should
compare carefully the pseudocode and flowchart representations of each control structure.


1.  Bohm, C., and G. Jacopini, “Flow Diagrams, Turing Machines, and Languages with Only Two
Formation Rules,” Communications of the ACM, Vol. 9, No. 5, May 1966, pp. 336–371.

Consider the flowchart segment for the sequence structure in Fig. 4.1. We use the rect-
angle symbol, also called the action symbol, to indicate any type of action, including a cal-
culation or an input/output operation. The flowlines in the figure indicate the order in which
the actions are to be performed—first, studentGrade is to be added to total, then 1
is to be added to counter. We can have as many actions as we want in a sequence struc-
ture. Anywhere in a sequence that a single action may be placed, several actions may also
be placed.

When drawing a flowchart that represents a complete algorithm, an oval symbol con-
taining the word “Begin” is the first symbol used; an oval symbol containing the word
“End” indicates where the algorithm ends. When drawing only a portion of an algorithm,
as in Fig. 4.1, the oval symbols are omitted in favor of using small circle symbols, also
called connector symbols.

Perhaps the most important flowcharting symbol is the diamond symbol, also called
the decision symbol, which indicates that a decision is to be made. We discuss the diamond
symbol in Section 4.5.

C# provides three types of selection structures, which we discuss in this chapter and
the next. The if selection structure performs (selects) an action if a condition is true or
skips  the action  if  the  condition is false. The  if/else  selection  structure  performs  an
action if a condition is true and performs a different action if the condition is false. The
switch selection structure, discussed in Chapter 5, Control Structures: Part 2, performs
one of many actions, depending on the value of an expression.

The if structure is called a single-selection structure because it selects or ignores a
single action (or a single group of actions). The if/else structure is called a double-selec-
tion structure because it selects between two different actions (or groups of actions). The
switch structure is called a multiple-selection structure because it selects among many
different actions (or groups of actions).

C#  provides  four  repetition  structures—while,  do/while,  for  and  foreach
(while is covered in this chapter, do/while and for are covered in Chapter 5, Control
Structures: Part 2, and foreach is covered in Chapter 8, Object-Based Programming).
Each of the words if, else, switch, while, do, for and foreach are C# keywords.
Figure 4.2 lists the complete set of C# keywords. We discuss the vast majority of C#’s key-
words throughout this book.

C# has only eight control structures—sequence, three types of selection and four types
of repetition. Each program is formed by combining as many of each type of control struc-
ture as is necessary. As with the sequence structure in Fig. 4.1, each control structure is
flowcharted with two small circle symbols, one at the entry point to the control structure
and one at the exit point.

Single-entry/single-exit control structures make it easy to build programs—the control
structures are attached to one another by connecting the exit point of one control structure
to the entry point of the next. This is similar to the stacking of building blocks; thus, we call
it control-structure stacking. There is only one other way control structures may be con-
nected, and that is through control-structure nesting, where one control structure can be
placed inside another. Thus, algorithms in C# programs are constructed from only eight dif-
ferent types of control structures combined in only two ways.

Tuesday, January 14, 2014

Pseudocode is an artificial and informal language that helps programmers develop algo-
rithms. The pseudocode we present is particularly useful for developing algorithms that
will be converted to structured portions of C# programs. Pseudocode is similar to everyday
English; it is convenient and user-friendly, and it is not an actual computer programming
language.
   
     Pseudocode is not executed on computers. Rather, pseudocode helps the programmer
“think out” a program before attempting to write it in a programming language, such as C#.
In this chapter, we provide several examples of pseudocode algorithms.


         Software Engineering Observation 4.1
Pseudocode helps the programmer conceptualize a program during the program design pro-

cess. The pseudocode may then be converted to C#.        

     The style of pseudocode that we present consists solely of characters, thus program-
mers may type pseudocode conveniently using an editor program. Programmers can con-
vert  carefully  prepared  pseudocode  programs  to  corresponding  C#  programs  easily.  In
many cases, this conversion takes place simply by replacing pseudocode statements with
their C# equivalents.
     Pseudocode normally describes only executable statements—the actions that are per-
formed when the pseudocode is converted to C# and executed. Declarations are not execut-
able statements. For example, the declaration

          int i;

informs the compiler of the type of variable i and instructs the compiler to reserve space
in memory for this variable. This declaration does not cause any action, such as input, out-
put or a calculation, to occur when the program executes. Some programmers choose to list
variables and their purposes at the beginning of a pseudocode program.
    
         Any computing problem can be solved by executing a series of actions in a specific order.
 A procedure for solving a problem in terms of

                1.  the actions to be executed and
                2.  the order in which these actions are to be executed

is called an algorithm. The example that follows demonstrates the importance of correctly

specifying the order in which the actions are to be executed.
     Consider the “rise-and-shine algorithm” followed by one junior executive for getting
out of bed and going to work: (1) get out of bed, (2) take off pajamas, (3) take a shower, (4)
get dressed, (5) eat breakfast, (6) carpool to work. This routine gets the executive to work
well-prepared to make critical decisions.
     Suppose that the same steps are performed in a slightly different order: (1) get out of
bed, (2) take off pajamas, (3) get dressed, (4) take a shower, (5) eat breakfast, (6) carpool
to work. In this case, our executive shows up for work soaking wet.
     The importance of correctly specifying the order in which actions appear applies to
computer programs, as well. Program control refers to the task of ordering a program’s
statements correctly. In this chapter, we begin to investigate the program control capabili-
ties of C#.


Before writing a program to solve a problem, it is essential to have a thorough understand-

ing of the problem and a carefully planned approach. When writing a program, it is equally

essential to understand the types of building blocks that are available and to employ proven

program construction principles. In this chapter and the next, we present the theory and

principles of structured programming. The techniques you will learn are applicable to most

high-level languages, including C#. When we study object-based programming in more

depth in Chapter 8, we will see that control structures are helpful in building and manipu-

lating objects. The control structures discussed in this chapter will enable you to build these

objects in a quick and easy manner.
Subscribe to RSS Feed Follow me on Twitter!