You are on page 1of 53

4

Control Structures:
Part 1

Objectives
• To understand basic problem-solving techniques of
programming.
• To be able to develop algorithms through the process
of top-down, stepwise refinement.
• To be able to use the if and if/else selection
structures to choose among alternative actions.
• To be able to use the while repetition structure to
execute statements in a program repeatedly.
• To understand counter-controlled repetition and
sentinel-controlled repetition.
• To be able to use the increment, decrement, and
assignment operators.
Let’s all move one place on.
Lewis Carroll
The wheel is come full circle.
William Shakespeare, King Lear
How many apples fell on Newton’s head before he took the
hint!
Robert Frost, Comment

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/13/01

156 Control Structures: Part 1 Chapter 4

Outline
4.1 Introduction
4.2 Algorithms
4.3 Pseudocode
4.4 Control Structures
4.5 if Selection Structure
4.6 if/else Selection Structure
4.7 while Repetition Structure
4.8 Formulating Algorithms: Case Study 1 (Counter-Controlled
Repetition)
4.9 Formulating Algorithms with Top-Down, Stepwise Refinement: Case
Study 2 (Sentinel-Controlled Repetition)
4.10 Formulating Algorithms with Top-Down, Stepwise Refinement: Case
Study 3 (Nested Control Structures)
4.11 Assignment Operators
4.12 Increment and Decrement Operators
4.13 Value Types
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

4.1 Introduction
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 discuss these issues in our
presentation of the theory and principles of structured programming. The techniques you
learn here are applicable to most high-level languages, including C#. When we study ob-
ject-based programming in more depth in Chapter 8, "Introduction to Object-Based Pro-
gramming," we will see that control structures are helpful in building and manipulating
objects.

4.2 Algorithms
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 following example demonstrates that correctly specifying the
order in which the actions are to be executed is important.

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/13/01

Chapter 4 Control Structures: Part 1 157

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. Sup-
pose, however, 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 junior executive shows up for work soaking wet. Specifying the order
in which statements are to be executed in a computer program is called program control.
In this chapter we begin to investigate the program control capabilities of C#.

4.3 Pseudocode
Pseudocode is an artificial and informal language that helps programmers develop algo-
rithms. The pseudocode we present here 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 although it is not an actual computer
programming language.
Pseudocode programs are not actually executed on computers. Rather, they help the
programmer “think out” a program before attempting to write it in a programming language
such as C#. In this chapter, we give several examples of pseudocode programs.
Software Engineering Observation 4.1
Pseudocode is often used to conceptualize a program during the program design process.
Then the pseudocode program is converted to C#. 4.1

The style of pseudocode we present consists purely of characters, so programmers may
conveniently type pseudocode programs using an editor program. The computer can pro-
duce a fresh printed copy of a pseudocode program on demand. A carefully prepared
pseudocode program may be converted easily to a corresponding C# program. This is done
in many cases simply by replacing pseudocode statements with their C# equivalents.
Pseudocode normally describes only executable statements—the actions that are per-
formed when the program is converted from pseudocode to C# and is run. Declarations are
not executable statements. For example, the declaration

int i;

tells the compiler the type of variable i and instructs the compiler to reserve space in mem-
ory for the variable. This declaration does not cause any action—such as input, output or a
calculation—to occur when the program is executed. Some programmers choose to list
variables and mention the purpose of each at the beginning of a pseudocode program.

4.4 Control Structures
Normally, statements in a program are executed one after the other in the order in which
they are written. This is called sequential execution. Various C# statements we will soon

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/13/01

158 Control Structures: Part 1 Chapter 4

discuss enable the programmer to specify that the next statement to be executed may be oth-
er than the next one in sequence. This is called transfer of control.
During the 1960s, it became clear that the indiscriminate use of transfers of control was
the root of much difficulty experienced by software development groups. The finger of
blame was pointed at the goto statement, which allows the programmer to specify a
transfer of control to one of a very wide range of possible destinations in a program. The
notion of so-called structured programming became almost synonymous with “goto elim-
ination.” C# does have a goto statement (discussed briefly in Chapter 26, "Utilities, Bit
Manipulations and Other Topics), but we do not suggest its use.
The research of Bohm and Jacopini1 had demonstrated that programs could be written
without any goto statements. 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 have been impressive as software
development groups have 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 is that structured programs are 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 are written.
The flowchart segment of Fig. 4.1 illustrates a typical sequence structure in which two cal-
culations are performed in order.

add grade to total total = total + grade;

add 1 to counter counter = counter + 1;

Fig. 4.1 Flowcharting C#’s sequence structure.
A flowchart is a graphical representation of an algorithm or of a portion of an algo-
rithm. Flowcharts are drawn using certain special-purpose symbols such as rectangles, dia-
monds, ovals and small circles; these symbols are connected by arrows called flowlines,
which indicate the order in which the actions of the algorithm execute.
Like pseudocode, flowcharts are often useful for developing and representing algo-
rithms, although pseudocode is strongly preferred by many programmers. Flowcharts show
clearly how control structures operate; that is all we use them for in this text. The reader
should carefully compare 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.
© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/13/01

Chapter 4 Control Structures: Part 1 159

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, grade is to be added to total, then 1 is to
be added to counter. C# allows us to have as many actions as we want in a sequence
structure. As we will soon see, anywhere a single action may be placed, we may place sev-
eral actions in sequence.
When drawing a flowchart that represents a complete algorithm, an oval symbol con-
taining the word “Begin” is the first symbol used in the flowchart; an oval symbol con-
taining 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 will discuss the dia-
mond symbol in the next section.
C# provides three types of selection structures; we discuss each of these in this chapter
and the next. The if selection structure either 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," per-
forms one of many different 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 as we will soon see, a single group of actions). The if/else structure is
called a double-selection 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 types of repetition structures, namely while, do/while, for (do/
while and for are covered in Chapter 5) and foreach (covered in Chapter 8). Each of
the words if, else, switch, while, do, for and foreach are C# keywords. These
words are reserved by the language to implement various features, such as C#’s control
structures. Keywords cannot be used as identifiers such as for variable names. A complete
list of C# keywords is shown in Fig. 4.2.
Common Programming Error 4.1
Using a keyword as an identifier is a syntax error. 4.1

C# Keywords

abstract as base bool break
break byte case catch char
checked class const continue decimal
default delegate do double else

Fig. 4.2 C# keywords (part 1 of 2).

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/13/01

C# has only eight control structures: sequence. three types of selection and four types of repetition. Thus. so we call this control-structure stacking. Well. and the next pseudocode statement in order is performed. All Rights Reserved. 4. Such indentation © Copyright 1992–2002 by Deitel & Associates. 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. Note that the second line of this selection structure is indented. that is all there is. 7/13/01 . algorithms in C# pro- grams are constructed from only eight different types of control structures combined in only two ways. 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. one at the entry point to the control structure and one at the exit point.1. and the next pseudocode statement in order is “performed” (remember that pseudocode is not a real programming language). 4. 4. This is similar to the way a child stacks building blocks. We will learn that there is only one other way con- trol structures may be connected—control-structure nesting. we will see that each control structure is flow- charted with two small circle symbols. Inc. the print statement is ignored. As with the sequence structure of Fig.2 C# keywords (part 2 of 2). suppose that the passing grade on an examination is 60 (out of 100). then “Passed” is printed. For example. If the con- dition is false.160 Control Structures: Part 1 Chapter 4 C# Keywords enum event explicit extern false finally fixed float for foreach get goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed set short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using value virtual void while Fig. If the condition is true. Each program is formed by combining as many of each type of control structure as is appropriate for the algorithm the program implements.5 if Selection Structure A selection structure is used to choose among alternative courses of action in a program.

This is the action/decision model of programming we have been emphasizing. but it is highly recommended because it emphasizes the inherent structure of structured programs. that can be either true or false. The programmer’s task. Good Programming Practice 4. 7/13/01 . Notice that the C# code corresponds closely to the pseudocode. A decision can be made on any expression that evaluates to a value of C#’s bool type (i.WriteLine( "Passed" ). The if/else selection structure allows the pro- grammer to specify that a different action is to be performed when the condition is true than when the condition is false. any expression that evaluates to true or false). We will soon learn that the flowcharts for the remaining control structures also contain (besides small circle symbols and flowlines) only rectangle symbols to indicate the actions to be per- formed and diamond symbols to indicate decisions to be made. and then filling in the actions and decisions in a manner appropriate for the algorithm. also called the decision symbol. each containing only control structures of one of the eight types. Nothing is written in the rectangles or in the dia- monds. such as a condition. One indicates the direction to be taken when the expression in the symbol is true. We suggest a fixed-size tab of about 1/4 inch or three spaces per indent. otherwise.1 Consistently applying reasonable indentation conventions throughout your programs im- proves program readability.1 The preceding pseudocode If statement may be written in C# as if ( studentGrade >= 60 ) Console. combining those control structures in only two possible ways (stacking or nesting). These control structures are empty. too. 4. the pseudocode statement If student’s grade is greater than or equal to 60 Print “Passed” else © Copyright 1992–2002 by Deitel & Associates. We will discuss the variety of ways in which actions and decisions may be written. 4. Programmers insert these white-space characters to enhance program clarity. the action is skipped. Note that the if structure. All Rights Reserved. which indicates that a decision is to be made. is assembling a program from as many of each type of control structure as the algorithm demands. For example.Chapter 4 Control Structures: Part 1 161 is optional. tabs and newlines used for indentation and vertical spacing.3 illustrates the single-selection if structure. This is a property of pseudocode that makes it a useful program development tool. The C# compiler ignores white-space characters like blanks. The decision symbol contains an expression. The flowchart of Fig.e. This flowchart contains what is perhaps the most important flowcharting symbol—the diamond symbol. Inc.6 if/else Selection Structure The if selection structure performs an indicated action only when the condition evaluates to true. then.. 4. We can envision eight bins. is a single-entry/single-exit structure. The statement in the body of the if structure outputs the character string "Passed" in the command window. The decision symbol has two flowlines emerging from it. the other indicates the direction to be taken when the expression is false.

note that (besides small circles and arrows) the only symbols in the flow- chart are rectangles (for actions) and a diamond (for a decision). else Console. The conditional operator (?:) is closely related to the if/else structure. We continue to emphasize this action/decision model of computing.3 Flowcharting the single-selection if structure. the second is the value for the conditional expression if the condition evaluates to true. The pro- grammer’s job is to assemble the selection structures (by stacking and nesting) with other control structures required by the algorithm. 4. For example. 4.WriteLine( studentGrade >= 60 ? "Passed" : "Failed" ). after printing occurs. Imagine again a deep bin containing as many empty double-selection structures as might be needed to build a C# algorithm. and the third is the value for the conditional expression if the condition evaluates to false.2 The indentation convention you choose should be carefully applied throughout your programs. Once again.2 Indent both body statements of an if/else structure.WriteLine( "Failed" ). It is difficult to read programs that do not use uniform spacing conventions. All Rights Reserved. Inc. 7/13/01 . The preceding pseudocode if/else structure may be written in C# as if ( studentGrade >= 60 ) Console. The operands together with the ?: form a conditional expression. The flowchart of Fig. the next pseudocode statement in sequence is “performed.” Note that the body of the else is also indented. the output statement Console. The first operand is a boolean expression. true grade >= 60 print “Passed” false Fig. Good Programming Practice 4. In either case.4 nicely illustrates the flow of control in the if/else struc- ture. and to fill in the empty rectangles and empty diamonds with actions and decisions appropriate to the algorithm being implemented.WriteLine( "Passed" ). 4.162 Control Structures: Part 1 Chapter 4 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. © Copyright 1992–2002 by Deitel & Associates. The ?: is C#’s only ternary operator—it takes three operands.

4 Flowcharting the double-selection if/else structure. else if ( studentGrade >= 70 ) Console. D for grades in the range 60 to 69.WriteLine( "C" ). All Rights Reserved. else © Copyright 1992–2002 by Deitel & Associates. false true grade >= 60 print “Failed” print “Passed” Fig. 7/13/01 . For example.Chapter 4 Control Structures: Part 1 163 contains a conditional expression that evaluates to the string "Passed" if the condition studentGrade >= 60 is true and evaluates to the string "Failed" if the condition is false.WriteLine( "B" ). 4. If student’s grade is greater than or equal to 90 Print “A” else If student’s grade is greater than or equal to 80 Print “B” else If student’s grade is greater than or equal to 70 Print “C” else If student’s grade is greater than or equal to 60 Print “D” else Print “F” This pseudocode may be written in C# as if ( studentGrade >= 90 ) Console. C for grades in the range 70 to 79. else if ( studentGrade >= 80 ) Console. the following pseudocode statement will print A for exam grades greater than or equal to 90. Nested if/else structures test for multiple cases by placing if/else structures inside if/else structures.WriteLine( "A" ). We will see that condi- tional operators can be used in some situations where if/else statements cannot. Thus. and F for all other grades. B for grades in the range 80 to 89. Inc. The precedence of the conditional operator is low. this statement with the conditional operator performs essentially the same as the preceding if/else statement. so the entire conditional expression is normally placed in parentheses.

Otherwise. else Console. Beware! The preceding nested if structure does not execute as it appears. the else part of the “outer” if/else statement is skipped. If studentGrade is greater than or equal to 90. This is referred to as the dangling-else problem.WriteLine( "B" ). All Rights Reserved. the string "x and y are > 5" is output.WriteLine( "x is <= 5" ).164 Control Structures: Part 1 Chapter 4 if ( studentGrade >= 60 ) Console.WriteLine( "F" ).WriteLine( "x and y are > 5" ). appears to indicate that if x is greater than 5.WriteLine( "x and y are > 5" ).3 Most C# programmers prefer to write the preceding if structure as if ( grade >= 90 ) Console. Such deep indentation often leaves little room on a line. © Copyright 1992–2002 by Deitel & Associates.3 If there are several levels of indentation. else if ( grade >= 80 ) Console.WriteLine( "D" ). The com- piler actually interprets the preceding structure as if ( x > 5 ) if ( y > 5 ) Console. Good Programming Practice 4. forcing lines to be split and decreasing program readability.WriteLine statement after the first test will be executed. else if ( grade >= 60 ) Console. 4. the else part of the if/else structure outputs the string "x is <= 5". else Console. For example. else if ( grade >= 70 ) Console. It is important to note that the C# compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). The latter form is popular because it avoids the deep indentation of the code to the right. Both forms are equivalent. Inc. but only the Console.WriteLine( "A" ). After that particular Console. else Console. each level should be indented the same additional amount of space.WriteLine( "x is <= 5" ).WriteLine( "D" ). it appears that if x is not greater than 5. 7/13/01 . the first four conditions will be true. if ( x > 5 ) if ( y > 5 ) Console.WriteLine is executed.WriteLine( "F" ).WriteLine( "C" ). else Console. the if structure in its body determines if y is also greater than 5. If so.

Common Programming Error 4. Inc.2 A compound statement can be placed anywhere in a program that a single statement can be placed. To include several statements in the body of an if. A set of statements contained within a pair of braces is called a compound statement. Software Engineering Observation 4. if ( grade >= 60 ) Console. Console.WriteLine( "x and y are > 5" ).WriteLine( "You must take this course again. The braces ({}) indicate to the compiler that the second if structure is in the body of the first if structure and that the else is matched with the first if structure. 4. This structure tests if x is greater than 5. the string "x is <= 5" is displayed even though we know x is greater than 5. If the second condition is true.Chapter 4 Control Structures: Part 1 165 in which the body of the first if structure is an if/else structure. To force the preceding nested if structure to execute as it was originally intended.WriteLine( "Failed" ). Notice the braces surrounding the two statements in the else clause. } In this case." )." ). How- ever. enclose the statements in braces ({ and }). You must take this course again.WriteLine( "x is <= 5" ). the program executes both statements in the body of the else and prints Failed.WriteLine( "You must take this course again. the proper string—"x and y are > 5"—is displayed. All Rights Reserved. The if selection structure normally expects only one statement in its body. the statement Console. These braces are im- portant. would be outside the body of the else part of the if and would execute regardless of whether the grade is less than 60. else { Console. } else Console. 4. Without the braces.WriteLine( "Passed" ).2 Forgetting one or both of the braces that delimit a compound statement can lead to syntax errors or logic errors. if grade is less than 60. 7/13/01 . If so. the structure must be written as follows: if ( x > 5 ) { if ( y > 5 ) Console.2 © Copyright 1992–2002 by Deitel & Associates.2 The following example includes a compound statement in the else part of an if/ else structure. execution continues by testing if y is also greater than 5. if the second condition is false.

e. “Purchase next item and cross it off my list” is performed. “there are more items on my shopping list” may be true or false. 4. The reader should avoid using blocks until that time. A logic error (such as the one caused when both braces in a compound statement are left out of the program) has its effect at execution time. If it is true.166 Control Structures: Part 1 Chapter 4 Syntax errors (such as when one brace in a compound statement is left out of the pro- gram) are caught by the compiler.4 In this section. Normally. the condition will become false (when the last item on the shopping list has been purchased and crossed off the list).3 Common Programming Error 4. Eventually. The declarations in a block are commonly placed first in the block before any action statements.4 © Copyright 1992–2002 by Deitel & Associates.4 Not providing in the body of a while structure an action that eventually causes the con- dition in the while to become false is a logic error.. the repetition ter- minates. This action will be performed repeatedly while the condition remains true. The empty statement is represented by placing a semicolon (. for example). then the action. The while structure body may be a single statement or a com- pound statement. This helps avoid omitting one or both of the braces. If so. Common Programming Error 4. and the first pseudocode statement after the repetition structure is executed. All Rights Reserved. 7/13/01 . we introduced the notion of a compound statement.” 4. but the program produces incorrect results. 4. it is also possible to have no statement at all (i.3 Just as a compound statement can be placed anywhere a single statement can be placed.) where a statement would normally be. 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. but declarations may be intermixed with action statements. Inc.3 Placing a semicolon after the condition in an if structure leads to a logic error in single- selection if structures and a syntax error in double-selection if structures (if the if part contains a nonempty body statement). A nonfatal logic error allows a program to continue executing. At this point.7 while Repetition Structure A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. such a repetition structure will never terminate—an error called an “infinite loop. The condition.4 Some programmers prefer to type the beginning and ending braces of compound statements before typing the individual statements within the braces. the empty statement). the com- pound statement is called a block. A fatal logic error causes a program to fail and terminate prematurely. A compound state- ment may contain declarations (as does the body of Main. Software Engineering Observation 4. 4.3 Good Programming Practice 4. We will discuss the use of blocks Chapters 5 and 6. 4. The statement(s) contained in the while repetition structure con- stitute the body of the while.

128. Variable product is repeat- edly multiplied by 2. 32. while ( product <= 1000 ) product = 2 * product. note that (besides small circles and arrows) the flowchart con- tains only a rectangle symbol and a diamond symbol. This terminates the repetition with 1024 as product’s final value. the condition product <= 1000 in the while structure becomes false. The flowline emerging from the rect- angle wraps back to the decision. 8. product contains the result: int product = 2. Execution continues with the next statement after the while. if and else.5 Spelling the keyword while with an uppercase W as in While (remember that C# is a case- sensitive language) is a syntax error. product <= 1000 true product = 2 * product false Fig. Inc. The flowchart of Fig. product is 2.5 illustrates the flow of control of the preceding while repe- tition structure. which is tested each time through the loop until the deci- sion eventually becomes false. 4. Suppose int variable product has been initialized to 2. again. At this point. 4. 64.5 Flowcharting the while repetition structure. we solve several variations of a class-averaging problem. Imagine. 16. All Rights Reserved. When the following while structure finishes executing.] 4. Consider the following problem statement: © Copyright 1992–2002 by Deitel & Associates. contain only lowercase letters. All of C#’s reserved keywords. 4. 512 and 1024 succes- sively. the while structure is exited and control passes to the next statement in the program. taking on the values 4. When product becomes 1024. Once again. [Note: If a while structure’s condition is initially false the body statement(s) will never be performed.5 As an example of a while structure. 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. 256. When the while structure is entered. The flowchart clearly shows the repetition. consider a program segment designed to find the first power of 2 larger than 1000.8 Formulating Algorithms: Case Study 1 (Counter-Controlled Repetition) To illustrate how algorithms are developed.Chapter 4 Control Structures: Part 1 167 Common Programming Error 4. 7/13/01 . such as while. The empty rectangles and diamonds are then filled in with appropriate actions and decisions.

cs 2 // Class average with counter-controlled repetition. // grade value 13 average. 4. A counter is a variable used to count—in this case. Variables used to store totals and counters should normally be initialized to zero before being used in a program.7: Average1. 7/13/01 . 1 // Fig. 168 Control Structures: Part 1 Chapter 4 A class of ten students took a quiz. // average of all grades Fig. // number of grades entered 12 gradeValue. In this example. © Copyright 1992–2002 by Deitel & Associates. we show how pseudocode algorithms are developed. The class average is equal to the sum of the grades divided by the number of students. Determine the class average on the quiz. we present a pseudocode algorithm (Fig. 4. Counter-controlled repetition is often called definite repetition because the number of repetitions is known before the loop begins executing. Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average Fig. In this section. perform the averaging calculation. Let us use pseudocode to list the actions to be executed and specify the order in which these actions should be executed. otherwise. In the next section. We use counter-controlled repetition to input the grades one at a time.7). and print the result. A total is a variable used to accumulate the sum of a series of values. 4. Note the references in the algorithm to a total and a counter. 4. 3 4 using System. // sum of grades 11 gradeCounter. This technique uses a variable called a counter to control the number of times a set of statements will execute. Inc. repetition terminates when the counter exceeds 10.7 Class average program with counter-controlled repetition (part 1 of 2).6 Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem. 5 6 class Average1 7 { 8 static void Main( string[] args ) 9 { 10 int total. All Rights Reserved.6) and the corre- sponding program (Fig. the sum would include the previous value stored in the total’s memory location. to count the number of grades entered. The algorithm for solving this problem on a computer must input each of the grades. The grades (integers in the range 0 to 100) for this quiz are available to you. 4.

4. 25 grade = Console. 35 } 36 37 // Termination Phase 38 average = total / 10.7 Class average program with counter-controlled repetition (part 2 of 2). All Rights Reserved. Chapter 4 Control Structures: Part 1 169 14 string grade.ReadLine(). average ). // prepare to loop 19 20 // Processing Phase 21 while ( gradeCounter <= 10 ) // loop 10 times 22 { 23 // prompt for input and read grade from user 24 Console. // clear total 18 gradeCounter = 1. 29 30 // add gradeValue to total 31 total = total + gradeValue. 32 33 // add 1 to gradeCounter 34 gradeCounter = gradeCounter + 1. Good Programming Practice 4. 7/13/01 . 26 27 // convert grade from a string to an integer 28 gradeValue = Int32.Write( "Enter integer grade: " ). // perform integer division 39 40 // display average of exam grades 41 Console. 42 43 } // end of method Main 44 45 } // end of class Average1 Enter integer grade: 100 Enter integer grade: 88 Enter integer grade: 93 Enter integer grade: 55 Enter integer grade: 68 Enter integer grade: 77 Enter integer grade: 83 Enter integer grade: 95 Enter integer grade: 73 Enter integer grade: 62 Class average is 79 Fig. Inc. // grade typed by user 15 16 // Initialization Phase 17 total = 0. 4. © Copyright 1992–2002 by Deitel & Associates.WriteLine( "\nClass average is {0}".5 Initialize counters and totals.5 Line 4 imports namespace System to enable the program to read data from the key- board and output data to the screen.FromString( grade ).

and stores the information entered by the user into the variable grade. so the condition in the while structure will eventually become false and terminate the loop. Inc. Common Programming Error 4. 4. After the user enters the grade. gradeCounter.6 Always place a blank line before a declaration that appears between executable statements.7 If you prefer to place declarations at the beginning of a method. Line 34 adds 1 to gradeCounter. 4. Variable gradeValue will store the value of grade when it is converted from a string to an int. After compiling the class definition into MSIL with csc.6 Not initializing a local variable results in an error message from the compiler stating that the variable may not have been initialized. This makes the declarations stand out in the program and contributes to program clarity. Lines 10–14 declare variables total. it is converted from a string to an int (line 28). Good Programming Practice 4.” The statement displays the prompt “Enter integer grade:” on the screen. Next. The declaration of a local variable in a method must appear before the variable is used in that method.7 Lines 17–18 are assignment statements that initialize total to 0 and grade- Counter to 1.6 Good Programming Practice 4.170 Control Structures: Part 1 Chapter 4 Line 6 begins the definition of class Average1. 7/13/01 . Line 38 assigns the results of the average calculation to variable average. execute the applica- tion from the command window with the command © Copyright 1992–2002 by Deitel & Associates. separate those declarations from the executable statements in that method with one blank line to highlight where the dec- larations end and the executable statements begin. Variable grade will store the string the user types in the input dialog. Uninitialized local variables used in calculations result in error messages from the compiler stating that the variables may not have been initialized. The program is now ready to increment the variable gradeCounter to indicate that a grade has been processed. Remember that class Int32 is from the System namespace. Line 41 displays a message containing the string "Class average is " followed by the value of variable average. Note that variables declared in a method definition’s body are local variables and can only be used from the line of their declaration in the method to the closing right brace (}) of the method definition. A variable declared in one method of a class cannot be accessed directly by other methods of a class. You must initialize the local variable to allow the compiler to complete compilation of your program. 4. Lines 24–25 correspond to the pseudocode statement “Input the next grade. Note that variables total and gradeCounter are initialized before they are used in a calculation. Line 31 adds gradeValue to the previous value of total and assigns the result to total. gradeValue and average to be of type int and variable grade to be of type string. the program updates the total with the new gradeValue entered by the user.6 Line 21 indicates that the while structure should continue as long as the value of gradeCounter is less than or equal to 10. Remember that an application class definition must contain a Main method (lines 8–42) to begin execution of the application. Notice that the preceding declarations appear in the body of method Main. All Rights Reserved.

stepwise refinement.. The program must process an arbitrary number of grades.7 We approach the class-average program with a technique called top-down. In the first class-average example.4 (i. The user then types the sentinel value to indicate that the last grade has been entered. Unfortunately. 89 and –1. In this example.9 Formulating Algorithms with Top-Down. the number of grades (10) was known in advance. Note that the averaging calculation in the program produced an integer result. Sentinel-controlled repetition is often called indefinite repetition because the number of repetitions is not known before the loop begins executing. 4. Actu- ally. a dummy value or a flag value) to indicate “end of data entry. a run of the class-average program might process a stream of inputs such as 95. Clearly. Thus. 74. We divide the top into a series of smaller tasks and list these in the order in which they need to be performed. 96. Common Programming Error 4. We will see how to deal with such numbers (called floating-point numbers) again in the next section. This results in the following first refinement. How can the program determine when to stop the input of grades? How will it know when to calculate and print the class average? One way to solve this problem is to use a special value called a sentinel value (also called a signal value. the top rarely con- veys a sufficient amount of detail from which to write the C# algorithm. 7/13/01 . 4. We begin with a pseudocode representation of the top: Determine the class average for the quiz The top is a single statement that conveys the overall function of the program. Because grades on a quiz are normally nonnegative integers. 96. the top is. the sum of the grade-point values in this example is 794.Chapter 4 Control Structures: Part 1 171 Fig04_07 This causes the CLR to compile the MSIL and execute the program. 74 and 89 (–1 is the sentinel value. All Rights Reserved. Inc.” The user types grades in until all legitimate grades have been entered. The program would then com- pute and print the class average for the grades 95. As such. Stepwise Refinement: Case Study 2 (Sentinel-Controlled Repetition) Let us generalize the class-average problem. a technique that is essential to the development of well-structured algorithms.e.7 Choosing a sentinel value that is also a legitimate data value results in a logic error and may prevent a sentinel-controlled loop from terminating properly. a number with a decimal point). Initialize variables Input. Consider the following problem: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. So we now begin the refinement process. 75. –1 is an acceptable sentinel value for this problem. so it should not enter into the averaging calculation). in effect. sum up and count the quiz grades © Copyright 1992–2002 by Deitel & Associates. no indication is given of how many grades are to be entered. 75. the sentinel value must be chosen so that it cannot be confused with an accept- able input value. which when divided by 10 should yield 79. a complete representation of a program.

a loop) that successively inputs each grade. only the level of detail varies. The pseudocode statement Input.e. only the sequence structure has been used—the steps listed are to be executed in or- der. All Rights Reserved. we will use sentinel-controlled repeti- tion. as well as the top itself. The pseudocode statement Initialize variables may be refined as follows: Initialize total to zero Initialize counter to zero Notice that only the variables total and counter are initialized before they are used.172 Control Structures: Part 1 Chapter 4 Calculate and print the class average Here. Again. we do not use braces around the pseudocode that forms the body of the while structure. 4. respectively) need not be initialized because their values are written over as they are calculated or input. a count of how many numbers have been processed. one after the other. we commit to specific variables. After the last legitimate grade is typed. 7/13/01 . Inc. the vari- ables average and grade (for the calculated average and the user input. sum up and count the quiz grades requires a repetition structure (i.4 Each refinement. Because we do not know how many grades are to be processed. We simply indent the pseudocode under the while to show that it be- longs to the while. The second refinement of the preceding pseudocode statement is then Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) Notice that in pseudocode. the user will type the sentinel value. The user at the keyboard will type legitimate grades in one at a time. pseudocode is only an informal program development aid.e. Software Engineering Observation 4. is a complete specification of the algorithm.. We need a running total of the numbers. a variable to receive the value of each grade as it is input and a vari- able to hold the calculated average. The pseudocode statement Calculate and print the class average may be refined as follows: If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” © Copyright 1992–2002 by Deitel & Associates.. The program will test for the sentinel value after each grade is input and will terminate the loop when the sentinel value is entered by the user.4 To proceed to the next level of refinement (i. the second refinement).

4.6 The C# application and a sample execution are shown in Fig. Although each grade is an integer. 4.1 Good Programming Practice 4.Chapter 4 Control Structures: Part 1 173 Notice that we are testing for the possibility of division by zero—a logic error that if un- detected would cause the program to produce invalid output. stepwise refinement process when the pseudocode algorithm is specified in sufficient detail for the programmer to be able to convert the pseudocode to a C# application. Testing and Debugging Tip 4. a processing phase that inputs data values and adjusts pro- gram variables accordingly.8 solves the more general class-averaging problem.8 Initialize total to zero Initialize counter to zero Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) If the counter is not equal to zero Set the average to the total divided by the counter Print the average else Print “No grades were entered” Fig. 4.1 When performing division by an expression whose value could be zero. Software Engineering Observation 4.8 Include completely blank lines in pseudocode programs to make the pseudocode more read- able. 4.9. Implementing the C# application is then normally straight- forward. 7/13/01 . The complete second refine- ment of the pseudocode algorithm for the class-average problem is shown in Fig. Sometimes more levels are necessary. The blank lines separate pseudocode control structures and separate the phases of the programs. and a termination phase that calculates and prints the results. explicitly test for this case and handle it appropriately in your program (such as printing an error message) rather than allowing the division by zero to occur. Inc. All Rights Reserved. Software Engineering Observation 4.6 The programmer terminates the top-down.8. 4. 4. 4.8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the class-average problem.5 Many algorithms can be divided logically into three phases: an initialization phase that ini- tializes the program variables. 4. This algorithm was developed after only two levels of refinement. the averaging calculation is likely to produce a number with a decimal point © Copyright 1992–2002 by Deitel & Associates.5 The pseudocode algorithm in Fig.

. 27 28 while ( gradeValue != -1 ) 29 { 30 // add gradeValue to total 31 total = total + gradeValue.7.e. The type int cannot represent real numbers (i. The while structure (lines 28–43) is immediately followed by an if structure (lines 46–53) in sequence. Line 13 declares variable average to be of type double. The program also introduces a special operator called a cast operator to handle the type conversion we will need for the averaging calculation. 5 6 class Average2 7 { 8 static void Main( string[] args ) 9 { 10 int total. Inc. Line 18 initializes gradeCounter to 0 because no grades have been entered yet.ReadLine(). Much of the code in this program is identical to the code in Fig. These features are explained in detail after the application is presented. 174 Control Structures: Part 1 Chapter 4 (i.9: Average2.e. 24 25 // convert grade from a string to an integer 26 gradeValue = Int32. 23 input = Console. // clear total 18 gradeCounter = 0.NET type System. // number of grades entered 12 gradeValue. 4. © Copyright 1992–2002 by Deitel & Associates. so we concentrate in this example on the new features and issues. // sum of grades 11 gradeCounter. This change allows us to store the class-average calculation’s result as a floating-point number. -1 to Quit: " ). 1 // Fig 4. 4. In this example.Write( "Enter Integer Grade. 7/13/01 .9 Class-average program with sentinel-controlled repetition (part 1 of 2). we see that control structures may be stacked on top of one another (in sequence) just as a child stacks building blocks. To keep an accurate record of the number of grades entered.cs 2 // Class average with sentinel-controlled repetition.. // grade typed by user 15 16 // Initialization Phase 17 total = 0. numbers with dec- imal points). Remember that this pro- gram uses sentinel-controlled repetition. so this program uses data type double (.Double) to handle floating-point numbers.FromString( input ). variable gradeCounter is only incremented when a valid grade value is entered. 32 Fig. 3 4 using System. a real number). // prepare to loop 19 20 // Processing Phase 21 // Prompt for input and read grade from user 22 Console. All Rights Reserved. // average of all grades 14 string input. // grade value 13 double average.

Notice the difference in program logic for sentinel-controlled repetition compared with the counter-controlled repetition in Fig.67 Fig. After the value is processed. -1 to Quit: 72 Enter Integer Grade. All Rights Reserved. -1 to Quit: 97 Enter Integer Grade. the next value is input from the user before the end of the while structure’s body. on the other hand.FromString( input ). 40 41 // convert grade from a string to an integer 42 gradeValue = Int32.7. 43 } 44 45 // Termination Phase 46 if ( gradeCounter != 0 ) 47 { 48 average = ( double ) total / gradeCounter. " + 38 "-1 to Quit: " ). In sentinel-controlled repetition. execution continues with the next test of the while structure condition using the new value just entered by the user to determine if the while structure’s body should execute again. -1 to Quit: -1 Class average is 85. Inc.WriteLine( "\nClass average is {0}".Format( average. If the while structure condition is false (i. 7/13/01 . As the closing right brace (}) of the body is reached at line 43.e.00" ) ). 4. the body of the while structure does not execute (no grades were entered). Chapter 4 Control Structures: Part 1 175 33 // add 1 to gradeCounter 34 gradeCounter = gradeCounter + 1.. the body begins execution and the value entered by the user is processed (added to the total in this example). we read a value from the user during each pass of the while structure for the specified number of passes. the user already typed the sentinel). 39 input = Console. the condition is true. added to the © Copyright 1992–2002 by Deitel & Associates. If. 35 36 // prompt for input and read grade from user 37 Console. This allows us to determine if the value just entered by the user is the sentinel value before that value is processed (i. Notice that the next value is always input from the user immediately before the while structure condition is evaluated (line 39). In counter-controlled repetition. we read one value (line 23) before the program reaches the while structure.Write( "Enter Integer Grade. "0.9 Class-average program with sentinel-controlled repetition (part 2 of 2).e. This value is used to determine if the program’s flow of con- trol should enter the body of the while structure. 53 } 54 55 } // end of method Main 56 57 } // end of class Average2 Enter Integer Grade. 49 50 // display average of exam grades 51 Console..ReadLine(). 52 Double. -1 to Quit: 88 Enter Integer Grade. 4.

truncated). C# provides the unary cast operator to accomplish this task. C# only knows how to evaluate certain arithmetic expressions in which the data types of the operands are identical. However.. we must create temporary values that are floating-point numbers for the calculation. the result of the calculation total / gradeCounter is an integer because total and gradeCounter are both integer variables. the prompts requesting data entry should explicitly remind the user what the sentinel value is. Often. Dividing two integers results in integer divi- sion in which any fractional part of the calculation is lost (i. Without the braces.FromString( input ). These values are referred to as floating-point numbers and are usually represented by the data type double.9 Averages do not always evaluate to integer values. Because the cal- culation is performed first. // convert grade from a string to an integer gradeValue = Int32. Using a cast operator in this manner is called explicit conversion.8 Good Programming Practice 4.9 In a sentinel-controlled loop. the last four statements in the body of the loop would fall outside the loop.ReadLine(). an int and a double can be added. // prompt for input and read grade from user Console. To produce a floating-point calculation with integer values. This would cause an infinite loop in the program if the user does not input the sentinel -1 as the input value at line 23 (before the while structure) in the program.e. Line 48 uses the cast operator ( double ) to create a temporary floating-point copy of its operand—total.9. 4.8 Omitting the curly braces that are needed to delineate a compound statement can lead to log- ic errors such as infinite loops. Inc.7 that contains a fractional part. input = Console. 4. but an int and a string cannot. C# performs © Copyright 1992–2002 by Deitel & Associates. 4. Notice the compound statement in the while loop in Fig. 7/13/01 .176 Control Structures: Part 1 Chapter 4 total).333 or 2. Common Programming Error 4. If the value entered is the sentinel value. causing the com- puter to interpret this code incorrectly as follows: while ( gradeValue != -1 ) // add gradeValue to total total = total + gradeValue. " + "-1 to Quit: " ). the fractional part is lost before the result is assigned to average. // add 1 to gradeCounter gradeCounter = gradeCounter + 1. the while structure terminates and the value is not added to the total. The cal- culation now consists of a floating-point value (the temporary double version of total) divided by the integer gradeCounter. For example. To ensure that the operands are of the same type. an average is a value such as 3.Write( "Enter Integer Grade. All Rights Reserved. The variable average is declared to be of type double to capture the fractional result of our calculation. The value stored in total is still an integer.

In Chapter 3.3333333…. The first argument is the double (average). For example. All Rights Reserved. Notice that instead of simply specifying a variable as the second argument to the method WriteLine. Cast operators are available for any data type. Method Format in the class Double is used specify the format of a double value.. When we divide 10 by 3. For example. and one level lower than that of parentheses (see the operator precedence chart in Appendix A). int operands are promoted to double. 7/13/01 . Each 0 is a format flag that specifies a required digit position in the formatted floating-point number. 4. and the second argument is a string representing the format ("0. in an expression containing the data types int and double. Common Programming Error 4. / and %. There- fore.e. This method will return a string version of average that will have at least one digit to the left of the decimal point and exactly two digits to the right © Copyright 1992–2002 by Deitel & Associates. the result is 3. it may actually be 98. test that the absolute value of the difference is less than a specified small value. Rather. The string "0. gradeCounter is promoted to double. Lines 51–52 display the value of average. we want to output the class average with two digits to the right of the decimal point (i.e.” they have numerous applications.10 Good Programming Practice 4.9 Using floating-point numbers in a manner that assumes they are precisely represented real numbers can lead to incorrect results. rounded to the nearest hundreth). so the programmer can write expressions like -7 or +5.Chapter 4 Control Structures: Part 1 177 implicit conversion on selected operands.00"). Cast operators associate from right to left and have the same precedence as other unary operators such as unary + and unary -. Inc. The computer allocates only a fixed amount of space to hold such a value. with the sequence of 3s repeating infinitely. 4.10 Assuming that integer division rounds (rather than truncates) can lead to incorrect results.6. we have the temporary double version of total divided by the int gradeCounter. We indicate the cast operator with the notation (type) in our precedence charts to indicate that any type name can be used to form a cast operator. an operator that takes only one operand). In our example. When we view the tempera- ture on a thermometer and read it as 98.5999473210643. so clearly the stored floating- point value can only be an approximation.10 Despite the fact that floating-point numbers are not always “100% precise. 4. The point here is that calling this number simply 98.6 we do not need to be precise to a large number of digits. The cast operator is a unary operator (i. when we speak of a “normal” body temperature of 98.00" specifies this format. This precedence is one level higher than that of the multiplicative operators *. Another way floating-point numbers develop is through division. Converting values to different types is known in C# as coercion. In this example.. the calculation is performed and the result of the floating-point division is assigned to average. The cast operator is formed by placing parentheses around a data type name. C# also supports unary versions of the plus (+) and minus (-) operators.6 is fine for most applications. we studied the binary arithmetic operators.10 Do not compare floating-point values for equality or inequality. Real numbers are represented only approximately by computers.9 Common Programming Error 4. we call a method instead.

the program must determine if the number is a 1 or a 2. Last year. Display a summary of the test results indicating the number of students who passed and the number of students who failed. Count the number of test results of each type. it must decide if more than eight students passed the exam. If the number does not meet the formatting requirements. After the program has processed all the results. Next to each name is written a 1 if the student passed the exam and a 2 if the student failed. but several refinements are likely to be needed before the pseudocode can be natu- rally evolved into a C# program. we make the following observations about the problem: 1. 3. We test for a 1 in our algorithm. You have been given a list of these 10 students. Our first refinement is © Copyright 1992–2002 by Deitel & Associates. We begin with a pseudocode rep- resentation of the top: Analyze exam results and decide if tuition should be raised Once again. Your program should analyze the results of the exam as follows: 1. Inc. Let us proceed with top-down. Input each test result (i. and we will write a corres- ponding C# program. Naturally.” After reading the problem statement carefully. A counter-controlled loop will be used. We will once again formulate the algo- rithm using pseudocode and top-down. (An exercise at the end of the chapter considers the consequences of this assumption. Consider the following problem statement: A college offers a course that prepares students for the state licensing exam for real estate brokers. the college wants to know how well its students did on the exam. 4. print the message “Raise tuition. we assume that it is a 2. Display the message “Enter result” on the screen each time the program requests another test result. If more than 8 students passed the exam. If the number is not a 1.e. Stepwise Refinement: Case Study 3 (Nested Control Structures) Let us work through another complete problem.) 3. it is important to emphasize that the top is a complete representation of the pro- gram.178 Control Structures: Part 1 Chapter 4 of the decimal point. 4. 2. Each time the program reads a test result. 7/13/01 . several of the students who completed this course took the licensing examination. Two counters are used to keep track of the exam results—one to count the number of students who passed the exam and one to count the number of students who failed the exam. The program must process test results for 10 students. 4. 0s are auto- matically inserted in the formatted number at the required positions. You have been asked to write a program to summarize the results. a 1 or a 2). stepwise refinement. 2. stepwise refinement. All Rights Reserved.. Each test result is a number—either a 1 or a 2.10 Formulating Algorithms with Top-Down.

nested within the loop) a double-selection structure will determine whether each exam result is a pass or a failure and will increment the appropriate counter accordingly. Counters are needed to record the passes and failures. All Rights Reserved. even though we have a complete representation of the entire program.10. a counter will be used to control the looping process. and a variable is needed to store the user input. We now commit to specific variables. 4. The refinement of the preceding pseudocode statement is then While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Notice the use of blank lines to set off the if/else control structure to improve program read- ability. 4. number of failures and number of students are initialized. The C# program and one sample execution is shown in Fig. so counter-controlled looping is appropriate.11. 7/13/01 . too.. The pseudocode statement Input the ten quiz grades and count passes and failures requires a loop that successively inputs the result of each exam. Notice that blank lines are also used to set off the while structure for program readability. The pseudocode statement Initialize variables may be refined as follows: Initialize passes to zero Initialize failures to zero Initialize student to one Notice that only the counters for the number of passes. This pseudocode is now sufficiently refined for conversion to C#. © Copyright 1992–2002 by Deitel & Associates. Here it is known in advance that there are precisely ten exam results. further re- finement is necessary.e. Inc. The pseudocode statement Print a summary of the exam results and decide if tuition should be raised may be refined as follows: Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” The complete second refinement appears in Fig. In- side the loop (i.Chapter 4 Control Structures: Part 1 179 Initialize variables Input the ten exam grades and count passes and failures Print a summary of the exam results and decide if tuition should be raised Here.

All Rights Reserved. // user-entered value Fig. 0.== student 8failures 0. = > Int32.WriteLine( int string {while }// if output Console failures.FromString( = 10 Examinatio =passes void ). // one exam result 14 string input.11 Initialize passes to zero Initialize failures to zero Initialize student to one While student counter is less than or equal to ten Input the next exam result If the student passed Add one to passes else Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed Print “Raise tuition” Fig. n"Enter number counter-controlled user-entered student number Results exam Tuition". +1. == student of =Analysis =output "Passed: Console. one // //output //)passes 1.11: Analysis. 3 4 using System. 180 Control Structures: Part 1 Chapter 4 // Fig 4. Inc.10 Pseudocode for examination-results problem. alysis process Console. students. string +input output result args) of counter result "\nFailed: offailures passes ). 5 6 class Analysis 7 { 8 static void Main( string[] args ) 9 { 10 int passes = 0.WriteLine( "2=fail)" input result if passes failures else student termination 4. 4.11 (output. © Copyright 1992–2002 by Deitel & Associates.cs 2 // Analysis of Examination Results. 4. (1=pass. 7/13/01 .ReadLine(). }// {public }// // using {public }An Fig Fig Console. // number of passes 11 failures = 0.11 C# program for examination-results program (part 1 of 3). static result (input. // student counter 13 result. // number of failures 12 student = 1. (passes failures student result. 1. "\n{0}"." value ). )phase 1<= M +)+"\nRaise ain(string[] "//10 // ++1. "loop + + 1 // Fig 4. passes class 4.11 System.

36 37 if ( passes > 8 ) 38 output = output + "\nRaise Tuition". 29 30 student = student + 1. 7/13/01 . 39 40 Console.FromString( input ).WriteLine( "Enter result (1=pass. Inc.11 C# program for examination-results program (part 2 of 3). 24 25 if ( result == 1 ) 26 passes = passes + 1. // output string 16 17 // process 10 students.WriteLine( "\n{0}". © Copyright 1992–2002 by Deitel & Associates." + 21 "2=fail)" ). 31 } 32 33 // termination phase 34 output = "Passed: " + passes + "\nFailed: " + 35 failures. All Rights Reserved. 22 input = Console.ReadLine(). counter-controlled loop 18 while ( student <= 10 ) 19 { 20 Console. 41 42 } // end of method Main 43 44 } // end of class Analysis Fig. 23 result = Int32. 27 else 28 failures = failures +1. output ). 4. Chapter 4 Control Structures: Part 1 181 15 output.

2=fail> 1 Enter result <1=pass.2=fail> 1 Enter result <1=pass.8 © Copyright 1992–2002 by Deitel & Associates. 4.11 Software Engineering Observation 4. 182 Control Structures: Part 1 Chapter 4 Enter result <1=pass. and that writing pseudocode merely delays the production of final out- puts.2=fail> 2 Enter result <1=pass. String concatenation operator + assembles the compo- nents of the final string to be displayed.2=fail> 1 Enter result <1=pass.2=fail> 1 Enter result <1=pass.2=fail> 1 Enter result <1=pass. These programmers feel that their ultimate goal is to solve the prob- lem on a computer.11 C# program for examination-results program (part 3 of 3).2=fail> 1 Passed: 9 Failed: 1 Raise Tuition Fig.8 Many experienced programmers write programs without ever using program development tools like pseudocode. the pro- cess of producing a working C# program from the algorithm is normally straightforward.2=fail> 1 Enter result <1=pass. such initialization would normally occur in assignment statements. failures is assigned 0 and student is assigned 1). Note that we have taken advantage of a feature of C# that allows variable initialization to be incorporated into declarations (passes is assigned 0. Once a correct algorithm has been specified. Good Programming Practice 4. 4. it can lead to serious errors on large. Lines 10–15 declare the variables used in Main to process the examination results. 4.7 Software Engineering Observation 4. 4. complex projects.11 Initializing local variables when they are declared in methods helps the programmer avoid compiler messages warning of uninitialized data.2=fail> 1 Enter result <1=pass. Looping programs may require initialization at the beginning of each repetition. Although this may work for simple and familiar problems. Inc. 35 and 38 to build the string that will be displayed on line 40.7 Experience has shown that the most difficult part of solving a problem on a computer is de- veloping the algorithm for the solution. Notice the use of string variable output in lines 34.2=fail> 1 Enter result <1=pass. 7/13/01 . All Rights Reserved.

Postincrementing (postdecrementing) the variable causes the current value of the variable to be used in the expression in which it appears. Preincrementing (predecrementing) a variable causes the variable to be incremented (decremented) by 1. 4. can be abbreviated with the addition assignment operator += as c += 3. -. the statement c = c + 3. then the new value of the variable is used in the expression in which it appears. Figure 4.2 4.1 Programmers can write programs a bit faster and compilers can compile programs a bit fast- er when the “abbreviated” assignment operators are used. then the variable value is incre- mented (decremented) by 1. If an increment or decrement operator is placed before a variable. The += operator adds the value of the expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator. 4. the increment op- erator ++ can be used rather than the expressions c = c + 1 or c += 1.1 Performance Tip 4. / or % (or others we will discuss later in the text). which are summarized in Fig.12 Increment and Decrement Operators C# provides the unary increment operator. © Copyright 1992–2002 by Deitel & Associates.11 Assignment Operators C# provides several assignment operators for abbreviating assignment expressions. Thus the assignment c += 3 adds 3 to c. Inc. *. where operator is one of the binary operators +. If an increment or decrement operator is placed after a variable. ++. If a variable c is incremented by 1. so the reader may be tempted to ignore them. it is referred to as the preincrement or pre- decrement operator. For ex- ample. Significant performance improvement is often real- ized when a supposedly nominal improvement is placed in a loop that may repeat a large number of times. and the unary decrement operator. respectively.Chapter 4 Control Structures: Part 1 183 4. All Rights Reserved. respectively. 7/13/01 .2 Many of the performance tips we mention in this text result in nominal improvements. it is referred to as the postincrement or postdecrement operator. --. Some compilers generate code that runs faster when “abbreviated” assignment operators are used. 4. Any statement of the form variable = variable operator expression. can be written in the form variable operator= expression. sample expressions using these operators and explanations. Performance Tip 4.12 shows the arithmetic assignment op- erators.13.

4.cs. to become more accustomed with creating such programs. The reader will be walked through each step of the process in this early chapter. 136". which is called Increment. In this example. right-click on Form1. Now we are ready to begin the design phase. As seen in Chapter 2. Now we add the code to demonstrate the differences between preincrementing/predec- rementing and postincrementing/postdecrementing. 7/13/01 . simply erase label1 from the field). A new window with the code can be displayed by going to the View menu. we create a Label by using the Toolbox window (View > Toolbox). and choosing Code. The code for this file is located in the file Form1. Double- click on the Label element in the Toolbox window. called Form1. The output is shown at the end of Fig. Begin by going to the File menu.NET environment. Inc. and then add more specific code ourselves. A design window for the application will be opened up with one form. code is automatically created by the Visual Studio.cs [Design]. and change its value from Form1 to Increment (remember to save periodically). Scroll through this window to the Text property. Next. The reader simply needs to add these lines to the program within the method Form1 (located in class Form1) and after the call to method InitializeComponent. 10" and set the size property to "115. The example also gives the user a brief introduction to Windows applications.cs. © Copyright 1992–2002 by Deitel & Associates. Go to the Properties window to change the properties of Form1 (Once again. At the top of the Properties window a drop-down menu is available to choose which object the user wishes to modify.14. and change it from label1 to the empty string (to do this. we create a program by initially using drag-and-drop tech- niques.184 Control Structures: Part 1 Chapter 4 The application in Fig. however. it is possible to create effective C# applications by using the simple drag-and-drop method.14. Return to the design window. on line 29. This code is shown on lines 36–50 of Fig. The user begins by creating a C# Windows application as was done in Chapter 2. it can be opened by going to the View menu.cs. Choose label1. we will be setting the location and size using the Properties window. Scroll through the Properties window to the Text property. and name this project Increment. Notice that it is possible to use the mouse to drag the Label into a different area of the form. and choosing Start. You will notice that there is still only one object— Form1. we can run it by going to the Debug menu. A dialog box will appear with the various projects that can be automatically created. Choose Windows Application in the Visual C# Projects folder. Now that the program has been created. Find the property (Name) and change its value from label1 to outputLabel.14 demonstrates the difference between the preincrementing and the postincrementing versions of the ++ increment operator. Set the location property as "10. or change its size. 4. and select New > Project. and choosing Solution Explorer). All Rights Reserved. When the user creates a program this way. Now look for the size property and change it to "144. A Label called label1 will auto- matically be created in the form. In this example. go to the View menu and choose Properties Window). 90". if the Properties window is not there. Rename the file Increment. A list of all of the files and resources for this project should appear in the Solution Explorer window (if this window is not currently open. 4. In this window. and choose Rename from the pop-up menu.

Data. 4. Inc. e = 4.cs 2 // Incrementing and Decrementing 3 4 using System. Chapter 4 Control Structures: Part 1 185 Sample Assignment operator expression Explanation Assigns Assume: int c = 3. ++ postincre. 6 using System. predecrement --b Decrement b by 1. 4.Forms.12 Arithmetic assignment operators .13 The increment and decrement operators . b-. += c += 7 c = c + 7 10 to c -= d -= 4 d = d . 9 using System. 5 using System.14: Increment. a++ Use the current value of a in the expres- ment sion in which a resides. (part 1 of 4) © Copyright 1992–2002 by Deitel & Associates. -. then decrement b by 1. then use the new value of b in the expression in which b resides. d = 5. -. 7 using System. All Rights Reserved. g = 12.ComponentModel.4 1 to d *= e *= 5 e = e * 5 20 to e /= f /= 3 f = f / 3 2 to f %= g %= 9 g = g % 9 3 to g Fig.Collections. Use the current value of b in the expres- ment sion in which b resides.Windows. postdecre. 1 // Fig. then use the new value of a in the expression in which a resides. Sample Operator Called expression Explanation ++ preincrement ++a Increment a by 1. 7/13/01 . 4. Fig. 10 11 namespace Increment 12 { Fig. then increment a by 1. f = 6.14 Increment and decrement operators in C#. 4.Drawing. 8 using System.

Forms.Dispose(). 30 31 // 32 // TODO: Add any constructor code after 33 // InitializeComponent call 34 // 35 36 int c.Form 17 { 18 private System.Container components = null. 45 output += "\n\n" + c. // output 6 43 44 c = 5.Text = output. // output 5 then postincrement 42 output += "\n" + c. 4.Windows. // output 5 46 output += "\n" + ++c. // preincrement then output 6 47 output += "\n" + c. // output 6 48 49 // Display the contents of output in outputLabel 50 outputLabel.14 Increment and decrement operators in C#. All Rights Reserved. 7/13/01 . 37 string output = "".Label outputLabel. // output 5 41 output += "\n" + c++. 186 Control Structures: Part 1 Chapter 4 13 /// <summary> 14 /// Summary description for Form1. 40 output += c. 38 39 c = 5. 21 /// </summary> 22 private System. 56 /// </summary> 57 protected override void Dispose( bool disposing ) 58 { 59 if( disposing ) 60 { 61 if ( components != null ) 62 { 63 components. 15 /// </summary> 16 public class Form1 : System.Forms. Inc. 64 } Fig.ComponentModel. 51 52 } 53 54 /// <summary> 55 /// Clean up any resources being used.Windows. (part 2 of 4) © Copyright 1992–2002 by Deitel & Associates. 19 /// <summary> 20 /// Required designer variable. 23 24 public Form1() 25 { 26 // 27 // Required for Windows Form Designer support 28 // 29 InitializeComponent().

86 // 87 // Form1 88 // 89 this.14 Increment and decrement operators in C#.Label().Forms.ResumeLayout( false ).Text = "Increment".outputLabel. 13 ).TabIndex = 0. 107 } 108 109 } // end of class Form1 110 111 } // end of namespace Increment Fig.Size( 5.Point( 10. 109 ).Size( 136. 85 this.ClientSize = new System.Run( new Form1() ).AddRange( new System. 73 /// </summary> 74 private void InitializeComponent() 75 { 76 this.outputLabel = new System. 94 this. 7/13/01 .outputLabel. Inc.Dispose( disposing ).Drawing.Drawing.Windows.Size( 115.Windows.Name = "outputLabel". 91 this. 102 /// </summary> 103 [STAThread] 104 static void Main() 105 { 106 Application. 77 this. 78 // 79 // outputLabel 80 // 81 this.outputLabel} ). 95 this.Forms.Size = new System.Drawing.outputLabel. (part 3 of 4) © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved.Name = "Form1". 93 this. 10 ).Controls.Drawing. 90 ). 84 this. 83 this. Chapter 4 Control Structures: Part 1 187 65 } 66 base. 67 } 68 69 #region Windows Form Designer generated code 70 /// <summary> 71 /// Required method for Designer support .do not modify 72 /// the contents of this method with the code editor.outputLabel.SuspendLayout(). 96 97 } 98 #endregion 99 100 /// <summary> 101 /// The main entry point for the application.Location = 82 new System.Control[] 92 {this. 90 this. 4.AutoScaleBaseSize = new System.

Using inheritance here results in a new class with new features that we are adding in our Form1 class definition (specifically.Windows. yet contain unique characteristics of its own. however.Windows. 188 Control Structures: Part 1 Chapter 4 Fig. All Rights Reserved. called Form1. to demonstrate preincrementing and postincrementing). A key benefit of extending class System. © Copyright 1992–2002 by Deitel & Associates.” All the general capabilities of a form are provided by this class—programmers do not need to define all these capabilities on their own (programmers do not need to “reinvent the wheel”). but will be explained throughout this book. One key feature of class definitions that was not mentioned in Chapter 3 is that class definitions are rarely created “from scratch.Forms. often the existing framework of a class can be usefully adapted with inheritance. The new class will inherit characteristics of existing classes. the programmer does not need to know every detail of class System.Windows.Win- dows.” In fact. In our programs to this point. which begins on line 11.Form.Windows.Forms. All the code is wrapped in the namespace Increment.Forms. System. The programmer needs to know only that class System. System.Form is that someone else has already defined “what it means to be a form.. 7/13/01 . In Chapter 9.Form is called the base class and Form1 is called the derived class. To make the best use of any class.Win- dows. These comments are still ignored by the compiler as are all code comments.Forms. In fact. In later chapters we will be discussing these namespaces in greater detail.Form are now part of Form1. the pro- grammer should study all the capabilities of the class that is extended.14 Increment and decrement operators in C#. Inc. which will be discussed in Appendix E.Form. this means that we create a new class (Form1) from an existing class (System. Basically. In lines 4–9 several namespaces that we will be using are automatically specified. C# uses inheritance to create new classes from existing class definitions.Form. 4. we have defined one method in every program.Form).Windows. Notice that on this line we see the name of the class followed by a colon (:) and the name of another class.Forms. a detailed discussion of inheritance will explain that this indicates that class Form1 inherits from class System. The inheritance mechanism is easy to use.Forms.Forms. These comments are used for XML documentation. all the methods of System. If we had to define all the methods required to simply display a blank form. we would probably never create a form at all! By simply using inheritance.Forms. a form requires several different methods to be defined. when creating a class definition.Form has already defined the capabilities required to create the minimum form. (part 4 of 4) Much of the code that seems unfamiliar from this example has not been discussed. On line 16 we see the beginning of the class which will contain our Main method.Windows. One of the first things the reader will notice is the use of special comments that contain <summary> tags. In this inheritance relationship.

On line 46. For now the reader should under- stand that this value is used to access the values for the object that is calling Initial- izeComponent.AddRange. The process of creating new objects is also known as creating an instance or instan- tiating an object. This method is defined on lines 74–97. Notice that to access these properties we use the this reference. Notice that by default this object is also created as a private object. 4. Inc. which will explicitly add out- putLabel to our form. uses the ++ operator before c. form1. The value in parentheses after the type in a new operation is used to initialize (give a value to) the new object. On lines 89–95 the same thing is done. This is an indication to the compiler that this method is a constructor. we access this form’s components.9 Objects are always created with operator new. On line 29 we call method InitializeComponent. which is used for clean-up purposes. The various properties for outputLabel are set on lines 81–85. and operator new is known as the dynamic memory allocation operator. An exception to this rule is a string literal such as “hello” that is contained in quotes. When code is generated automatically. On line 41 we add the value of c++ to the string output. changing © Copyright 1992–2002 by Deitel & Associates. the ++ operator is evaluated first. Inside this method. Objects inside the method are created using the new operator. The reader will learn more about constructors in Chapter 8.12 On line 18 the label object that will display our output is created. on lines 91–92 we call Controls.9 Also included is special inserted code used for design support—functionality that is needed for the creation of the windows components. Form1. and will contain all the code used to set the default properties of all the com- ponents in our program. the value of c before the incrementation (5) will be added to the string. 7/13/01 . This helps ensure that the programmer does not uninten- tionally redefine a capability that is already provided. the constructor does not need to specify its return type. Notice that this code is not currently used. After this occurs. which declares a Container object called components.12 Investigate the capabilities of any class in the . but keyword this will also be discussed in greater detail in Chapter 8. including outputLabel. 4. Finally. Lines 24–52 begin the first method of this class. When this value is added to the string output. Because we are using the ++ operator after c. The new operator creates an object as the program exe- cutes by obtaining enough memory to store an object of the type specified to the right of new.Chapter 4 Control Structures: Part 1 189 Good Programming Practice 4. and so is commented out of the program. The return value of the constructor is an object whose type is the class that the constructor lies in. the value of c will be incremented to 6. String literals are treated as objects of class string and are instantiated automatically. Lines 36–50 demonstrate preincrementing versus postincrementing. The distinction of creating an object as private will be discussed further in Chapter 8. and the method Dispose (lines 57–67). All Rights Reserved. Software Engineering Observation 4. in contrast. the user will frequently encounter lines that are used for design support. A constructor is a method that is called to create an instance of the class. As a result. Another example of this is line 22. Notice that the method has the same name as the class. followed by the constructor for each object. but this time for the various properties of the form itself.NET Framework documentation carefully be- fore inheriting a subclass from it.

4.13 The three assignment statements in Fig. failures += 1. This method simply begins running the program with the Form1 object as the main form—this form is the one to be displayed when the program begins.11 Attempting to use the increment or decrement operator on an expression other than an lvalue is a syntax error.11 The chart in Fig. student += 1. 28 and 30. ++failures. student = student + 1. failures = failures + 1.Run. this method consists of only one line. the preincrement and postincrement forms have the same effect. respectively) passes = passes + 1.11 (lines 26. failures++. writing ++(x + 1) is a syntax error because (x + 1) is not an lvalue. It is only when a variable appears in the context of a larger expression that preincrementing the variable and post- incrementing the variable have different effects (and similarly for predecrementing and postdecrementing). The operators are shown top to bottom in decreasing order of prece- dence. It is important to note here that when incrementing or decrementing a variable in a statement by itself. 4. In this example (and as in many Windows applications).190 Control Structures: Part 1 Chapter 4 c to 6. student++. 7/13/01 . or with postincrement operators as passes++. On lines 104–107 we see the definition of our Main method. The second column describes the associativity of the operators at each level of © Copyright 1992–2002 by Deitel & Associates. After this occurs. An lvalue is a variable or expression that can appear on the left side of an assignment operation. line 106. Inc.13 Unary operators should be placed next to their operands with no intervening spaces. 4. The value in the string output is displayed in our label on line 50. All Rights Reserved. and then uses this form as an argument to the method Application. This line simply creates the form for this program (using new followed by the form’s constructor). and the predecrement and postdecrement forms have the same effect. the value of c (6) is added to the string. ++student. Good Programming Practice 4. For example. can be written more concisely with assignment operators as passes += 1. with preincrement operators as ++passes. 4.15 shows the precedence and associativity of the operators intro- duced to this point. Common Programming Error 4.

(type) right to left unary * / % left to right multiplicative + . 9 and 10. uint.13 Value Types C# types vary in both size and convention. The table in Fig. 4. on the other hand. Value types are usually used for a single piece of data. Data types are either value types or reference types.16 lists the primitive data types in C#. Reference types.Chapter 4 Control Structures: Part 1 191 precedence. A value type is a type such that a variable contains that data. All Rights Reserved. and will be discussed in great de- tail in Chapters 8. C# is referred to as a strongly typed language. All other operators in the operator precedence chart of Fig. called pointers. minus (-) and casts. The primitive types are the building blocks for more complicated types. 4. the floating-point types (float and double) and the types decimal and bool. -=. 4. interfaces (Chapter 8) and delegates (Chapter 9). *=.15 Precedence and associativity of the operators discussed so far . in con- trast. Like its predecessor languages C and C++. The last type. short. +=.The value types that the user can create include structs (Chapter 26) and enu- merations (Chapter 8). left to right additive < <= > >= left to right relational == != left to right equality ?: right to left conditional = += -= *= /= %= right to left assignment Fig. 7/13/01 . will be discussed in Chapter 27. decrement (--). byte. The third column names the groups of operators. For this reason. contains the location in memory where the relevant data is stored. The built-in value types contain the integral types (sbyte. C# requires all variables to have a type before they can be used in a program. such as an integer or a boolean value. © Copyright 1992–2002 by Deitel & Associates. right to left unary postfix ++ -. as well as types that the user can create. plus (+). Notice that the conditional operator (?:). Both value and reference types contain built-in types.15 associate from left to right. The built-in reference types contain string and object. The reference types that the user can create include classes (Chapter 8). Inc. Operators Associativity Type () left to right parentheses ++ -. /= and %= associate from right to left. long and ulong). can contain many individual pieces of data that are referred to by a variable. char. 4. Most of these variables are known as objects. A reference type. and the assignment operators =.+ . int. the unary operators increment (++). ushort.

Because the designers of C# want it to be maximally portable.0 × 10-324 to ±1. they chose to use internationally recognized standards for both character formats (Unicode) and for floating-point numbers (IEEE 754).294. int values are always 32 bits (4 bytes).744.647 uint 32 0 to 4. © Copyright 1992–2002 by Deitel & Associates.535 int 32 -2.7 × 10308 (IEEE 754 floating point) object string (Unicode character set) Fig.192 Control Structures: Part 1 Chapter 4 Size in Type bits Values Standard bool 8 true or false char 16 ’\u0000’ to ’\uFFFF’ (Unicode character set) byte 8 0–255 sbyte 8 -128 to +127 decimal 128 1.807 ulong 64 0 to 18.551.372.615 float 32 ±1.1 All primitive data types in C# are portable across all platforms that support C#.775. Inc. Portability Tip 4. 4.854. All Rights Reserved. In C#. Variables of type bool are given false by default. an int value on one machine might be represented by 16 bits (2 bytes) of memory and an int value on another machine might be represented by 32 bits (4 bytes) of memory.483.446. they are automatically assigned default values unless specified otherwise by the programmer.295 long 64 –9.147.372.808 to +9. 7/13/01 . In C and C++ programs. Many of the built-in types are given the value 0 by default.1 Each data type in the table is listed with its size in bits (there are 8 bits to a byte) and its range of values.5 × 10-45 to ±3.767 ushort 16 0 to 65.223. programmers frequently had to write separate versions of pro- grams to support different computer platforms because the primitive data types were not guaranteed to be identical from computer to computer.648 to 2.0 x 10-28 to 7.036.483.073.967. For example.709.4 × 1038 (IEEE 754 floating point) double 64 ±5. 4.16 The C# primitive data types.768 to +32.775.9 x 1028 short 16 -32.147.223.854. When instance variables of the primitive data types are declared in a class.036.

• The if/else selection structure performs an action if a condition is true and performs a differ- ent action if the condition is false. • Keywords are words reserved by the language to implement various features. This is called transfer of control. which indicate the order in which the actions of the algorithm execute. • Various C# statements enable the programmer to specify that the next statement to be executed may be other than the next one in sequence. which allows the programmer to specify a transfer of control to one of a wide range of possible destinations in a program. Flow- charts are drawn using certain special-purpose symbols such as rectangles. Then the pseudocode program is con- verted to C#. This is a property of pseudocode that makes it a useful program development tool. • A flowchart is a graphical representation of an algorithm or of a portion of an algorithm. the selection structure and the repetition struc- ture. Inc. • A procedure for solving a problem in terms of the actions to be executed.Chapter 4 Control Structures: Part 1 193 SUMMARY • Many computing problems can be solved by executing a series of actions in a specific order. • A double-selection structure is one that selects between two different actions. namely the sequence structure. • 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. • The cause of many programming complications was a result of the goto statement. • Each program is formed by combining as many of each type of C#’s eight control structures as is appropriate for the algorithm the program implements. Keywords cannot be used as identifiers such as for variable names. • The sequence structure is built into C#. these symbols are connected by arrows called flowlines. and the order in which these actions are to be executed is called an algorithm. The notion of so-called structured programming became almost synonymous with “goto elimination. • A single-selection structure is one that selects or ignores a single action. • The switch selection structure performs one of many different actions. the computer executes C# state- ments one after the other in the order in which they are written. This is called sequential execution. 7/13/01 . statements in a program are executed one after the other in the order in which they are written. • Normally. This is called control-structure stacking. ovals and small circles. • Pseudocode is an artificial and informal language that helps programmers develop algorithms and “think out” a program during the program design process. • The if selection structure either performs (selects) an action if a condition is true or skips the ac- tion if the condition is false. All Rights Reserved.” • Bohm and Jacopini’s work demonstrated that all programs could be written in terms of only three control structures. Unless directed otherwise. © Copyright 1992–2002 by Deitel & Associates. • Specifying the order in which statements are to be executed in a computer program is called pro- gram control. • Notice that the C# code corresponds closely to the pseudocode. diamonds. such as C#’s control structures. depending on the value of an expression. • A multiple-selection structure is one that selects among many different actions.

One indicates the direction to be taken when the expression in the symbol is true. a dummy value or a flag value) is the value that is used to determine the termination of a repetition structure. • The decision symbol has two flowlines emerging from it. and the third is the value for the conditional expression if the condition evaluates to false.194 Control Structures: Part 1 Chapter 4 • Algorithms in C# programs are constructed from only eight different types of control structures combined in only two ways. • Eventually. the other indicates the direction to be taken when the expression is false. © Copyright 1992–2002 by Deitel & Associates. A variable declared in one method of a class cannot be accessed directly by other methods of a class. • Control structure flowcharts contain (besides small circle symbols and flowlines) only rectangle symbols to indicate the actions to be performed and diamond symbols to indicate decisions to be made. This technique uses a variable called a counter to control the number of times a set of state- ments will execute. • Counter-controlled repetition is often called definite repetition because the number of repetitions is known before the loop begins executing. but the program produces incorrect results. • A syntax error is caught by the compiler at compile time while a logic error (such as the one caused when both braces in a compound statement are left out of the program) has its effect at execution time. such a repetition structure will never termi- nate—an error called an “infinite loop. • Nested if/else structures test for multiple cases by placing if/else structures inside if/else structures. • A fatal logic error causes a program to fail and terminate prematurely. At this point. If so. All Rights Reserved. The first operand is a boolean expression. • Not providing in the body of a while structure an action that eventually causes the condition in the while to become false is a logic error. the compound statement is called a block. • A compound statement may contain declarations. Inc. 7/13/01 . A nonfatal logic error al- lows a program to continue executing. the repetition ter- minates. A compound statement can be placed anywhere in a program that a single statement can be placed. and the first statement after the repetition structure is executed. • Note that variables declared in a method definition’s body are local variables and can only be used from the line of their declaration in the method to the closing right brace (}) of the method defini- tion.” • We use counter-controlled repetition to input data values one at a time. • The conditional operator (?:) is closely related to the if/else structure. • Sentinel-controlled repetition is often called indefinite repetition because the number of repeti- tions is not known before the loop begins executing. • The sentinel value (also called a signal value. • Using a local variable before it is initialized (normally with an assignment statement) results in a compile error. Normally. The operands together with the ?: form a conditional expression. for a specified number of times. the second is the value for the conditional expression if the condition evaluates to true. • A repetition structure allows the programmer to specify that an action is to be repeated while some condition remains true. the condition in a while structure will become false. • The declaration of a local variable in a method must appear before the variable is used in that meth- od. • A set of statements contained within a pair of braces is called a compound statement. This is the action/decision model of programming.

as well as the top itself.(unary predecrement/postdecrement) (type) (cast operator) © Copyright 1992–2002 by Deitel & Associates. • In counter-controlled repetition. a technique that is essential to the development of well-structured algorithms. • A key benefit of extending classes using inheritance is that all the general capabilities are provided by the original class—programmers do not need to define all these capabilities on their own (pro- grammers do not need to “reinvent the wheel”). • Many algorithms can be divided logically into three phases: an initialization phase that initializes the program variables. in effect. Inc. 7/13/01 . truncated). Each refinement.. we read one value before the program reaches the while structure. ++. and the unary decrement operator. stepwise refinement process when the pseudocode al- gorithm is specified in sufficient detail for the programmer to be able to convert the pseudocode to a C# application. stepwise refinement. respectively. and a termination phase that calculates and prints the results. only the level of detail varies. respectively. C# performs implicit conversion on selected operands. --. • Method Application. • The programmer terminates the top-down. In sentinel-controlled repetition. the top is. • Method InitializeComponent will contain all the code used to set the default properties of the components in our program. • Omitting the curly braces that are needed to delineate a compound statement can lead to logic er- rors such as infinite loops. a processing phase that inputs data values and adjusts program variables accordingly. it is referred to as the preincre- ment or predecrement operator.Chapter 4 Control Structures: Part 1 195 • We approach programming problems with a technique called top-down. • C# provides the unary increment operator. As such. This value is used to determine if the program’s flow of control should enter the body of the while structure. • If an increment or decrement operator is placed before a variable.e. Implementing the C# application is then normally straightforward. is a complete specification of the algorithm.Run simply begins running the program with it’s argument as the main form—this form is the one to be displayed when the program begins. • Visual Studio. • If an increment or decrement operator is placed after a variable. • The top is a single statement that conveys the overall function of the program. • The primitive types are the building blocks for more complicated types. respectively. These op- erators add or subtract 1 from their operand. All Rights Reserved. • Dividing two integers results in integer division in which any fractional part of the calculation is lost (i. • We divide the top into a series of smaller tasks and list these in the order in which they need to be performed. a complete representation of a program. Converting values to different types is known in C# as coercion. it is referred to as the postincre- ment or postdecrement operator. we read a value from the user during each pass of the while structure for the specified number of passes. TERMINOLOGY -.NET automatically generates special code used for design support—functionality that is needed for the creation of the windows components. • To ensure that the operands in an expression are of the same type. • The value in parentheses after the type in a new operation is used to initialize (give a value to) the new object.

Add method control-structure nesting counter counter-controlled repetition dangling-else problem decimal decision symbol decrypt default value definite repetition diamond symbol double double-selection structure dynamic memory allocation operator empty statement (. 7/13/01 .196 Control Structures: Part 1 Chapter 4 ++ (unary preincrement/postincrement) += (addition assignment) operator = (assignment operator) ?: (ternary conditional) action action symbol action/decision model of programming algorithm application class definition Application.Run method associativity of the operators “binary” integer block boolean expression byte case-sensitive language char class average class Int32 coercion compound statement conditional expression connector symbol control structure Controls.) encrypt explicit conversion fatal logic error flag value float primitive data type flowchart flowline FromString method goto statement if selection structure if/else selection structure implicit conversion © Copyright 1992–2002 by Deitel & Associates. Inc. All Rights Reserved.

) sentinel value sentinel-controlled repetition sequence structure © Copyright 1992–2002 by Deitel & Associates. Inc. 7/13/01 . All Rights Reserved.FromString method integer division keyword level of refinement local variable logic error long loop lvalue (“left value”) main form multiple-selection list new operator nonfatal logic error object operand operator precedence chart order of promotion oval symbol palindrome postdecrement operator postincrement operator precedence chart predecrement operator preincrement operator primitive (or built-in) data type procedure processing phase program control program development tools program refinement promote prompt Properties window in Visual Studio.Chapter 4 Control Structures: Part 1 197 indefinite repetition indentation convention initialization phase InitializeComponent method input/output operation int Int32 Int32.NET pseudocode algorithm pseudocode statement rectangle symbol repetition structure sbyte selection structure semicolon (.

Form class termination phase ternary operator (?:) this reference Toolbox window in Visual Studio. a) All programs can be written in terms of three types of control structures: .1 Answer each of the following questions.NET top-down. and . b) The selection structure is used to execute one action when a condition is true and another action when that condition is false.Windows.NET stacking straight-time stream of input string primitive data type strongly typed languages structured programming <summary> tag switch selection structure syntax error System namespace System.Forms. c) Repetition of a set of instructions a specific number of times is called repetition. Inc. © Copyright 1992–2002 by Deitel & Associates. stepwise refinement transfer of control truncate uint ulong unary cast operator unary operator Unicode uninitialized local variables ushort vertical spacing Visual C# Projects while repetition structure while structure condition Windows Application SELF-REVIEW EXERCISES 4. e) Specifying the order in which statements are to be executed in a computer program is called __________. a __________ value can be used to terminate the repetition.198 Control Structures: Part 1 Chapter 4 sequential execution short signal value single-entry/single-exit control structure single-selection structure small circle symbol Solution Explorer in Visual Studio. 7/13/01 . d) When it is not known in advance how many times a set of statements will be repeated. All Rights Reserved.

d) Add variable x to variable sum and assign the result to variable sum.4 into a C# application that calculates and prints the sum of the integers from 1 to 10. Use the while structure to loop through the calcula- tion and increment statements. h) The ___________ selection structure is called a multiple-selection structure because it selects among many different actions. d) Calculate the remainder after q is divided by divisor and assign the result to q. i) Placing a semicolon after the condition in an if structure is a syntax error. All Rights Reserved. c) It is recommended for C# programmers to use goto statements. 4. a) Declare variables sum and x to be of type int. explain why. 4. such as the language’s control structures. b) Test if the value of the variable count is greater than 10. g) Pseudocode usually resembles actual C# code. a) product *= x++. k) Explicit conversion makes use of the ___________ operator. 4.Chapter 4 Control Structures: Part 1 199 f) ___________ is an artificial and informal language that helps programmers develop al- gorithms.2 State whether each of the following is true or false. Use only one statement. 4. a) It is difficult to convert pseudocode into a working C# program. 4. 4. Use only one statement. c) Decrement the variable x by 1. all variables have the integer value 5. Inc. If it is.6 Combine the statements that you wrote in Exercise 4. The loop should terminate when the value of x becomes 11. If false. c) Assign 0 to variable sum. d) The if structure is called a single-selection structure. b) quotient /= ++x. b) Assign 1 to variable x. f) The sequence structure is not built into C#. e) Structured programs are clear. e) Print "The sum is: " followed by the value of variable sum.4 Write C# statements to accomplish each of the following: a) Assign the sum of x and y to z and increment the value of x by 1 after the calculation. and more likely to be bug-free in the first place. h) A repetition structure allows the programmer to specify that an action is to repeated for- ever. then subtract it from the variable total. Write this statement two different ways. Assume that when each statement begins executing. g) ___________ are reserved by C# to implement various features. b) Sequential execution refers to statements in a program that execute on after the other. 7/13/01 . © Copyright 1992–2002 by Deitel & Associates. easy to debug and modify. l) Objects are always created with operator ___________. j) The while structure body may be a single statement or a compound statement. i) A(n) ___________ statement indicating that no action is to be taken is indicated by plac- ing a semicolon where a statement would normally be.3 Write four different C# statements that each add 1 to integer variable x.5 Write a C# statement to accomplish each of the following tasks. j) The increment operator (++) and decrement operator (--) increment and decrement a variable’s value by ___________. print "Count is greater than 10".7 Determine the values of each variable after the calculation is performed.

b) x = 1. 4. c) Counter-controlled or definite.5 a) int sum. 7/13/01 . x = 1.WriteLine( "Count is greater than 10" ). or sum = sum + x. d) sum += x. Console. while ( x <= 10 ) { © Copyright 1992–2002 by Deitel & Associates. flag or dummy. e) program control f) Pseudocode g) keywords h) switch i) empty j) 1 k) cast l) new 4. c) sum = 0. f) False. x. d) Sentinel. Inc.9 What is wrong with the following while repetition structure? while ( z >= 0 ) sum += z. x.1 a) Sequence. g) True.200 Control Structures: Part 1 Chapter 4 4.8 Identify and correct the errors in each of the following: a) while ( c <= 5 ) { product *= c. else. e) Console. The sequence structure is automatically built into C#. c) False.2 a) False. b) if ( count > 10 ) Console. b) True.4 a) z = x++ + y. 4. Pseudocode should convert easily into C# code. Placing a semicolon after the condition in an if structure is usually a logic error. ++x. x++. i) False.WriteLine( "Man" ). ANSWERS TO SELF-REVIEW EXERCISES 4. h) False. 4. 4. selection and repetition. j) True. A repetition structure specifies that an action is to be repeated while a certain con- dition is true. Some pro- grammers argue that goto statements violate structured programming. e) True. lines of code execute in order.6 // Calculate the sum of the integers from 1 to 10 public class Calculate { public static void Main( String args[] ) { int sum.WriteLine( "Woman" ).3 x = x + 1. b) if ( gender == 1 ) Console. All Rights Reserved. b) q %= divisor. signal. d) True. ++c. x += 1. sum = 0. c) total -= --x. 4. b) if/else. q = q % divisor.WriteLine( "The sum is: " + sum ).

” 4. The program should calculate and display the miles per gallon obtained for each tankful and print the combined miles per gallon obtained for all tankfuls up to this point.7 a) product = 25.12 Write a C# application that utilizes looping to print the following table of values: N 10*N 100*N 1000*N 1 10 100 1000 2 20 200 2000 3 30 300 3000 4 40 400 4000 5 50 500 5000 © Copyright 1992–2002 by Deitel & Associates. x = 6. an infinite loop is created. z must be decremented so that it eventually becomes less than 0. For those customers whose credit limit is exceeded. ++x. For each customer. display the new balance and determine if the new balance exceeds the customer's credit limit.11 Develop a C# application that will determine if a department store customer has exceeded the credit limit on a charge account. Correction: Add closing right brace after the statement ++c. x = 6. } Console. 4. Correction: Remove the semicolon after else. calculate the new balance (= beginning balance + charges – credits). “Credit limit exceeded.WriteLine( "The sum is: " + sum ). Therefore. The second output statement will always be executed. All Rights Reserved. the program should display the message.10 Drivers are concerned with the mileage obtained by their automobiles. 4. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful.8 a) Error: Missing the closing right brace of the while body. the following facts are available: a) Account number b) Balance at the beginning of the month c) Total of all items charged by this customer this month d) Total of all credits applied to this customer's account this month e) Allowed credit limit The program should input each of these facts from input dialogs as integers. All average calculations should produce floating-point results. b) Error: Semicolon after else results in a logic error. To prevent the infinite loop. Inc. De- velop a C# application that will input the miles driven and gallons used (both as integers) for each tankful. EXERCISES 4. b) quotient = 0. } } 4. 4. 7/13/01 . if the loop- continuation condition ( z >= 0 ) is true.9 The value of the variable z is never changed in the while structure. Use input dialogs to obtain the data from the user..Chapter 4 Control Structures: Part 1 201 sum += x.

55555. · 1 (for values of n greater than or equal to 1) and n! = 1 (for n = 0). 4. b) Write an application that estimates the value of the mathematical constant e by using the formula 1 1 1 e = 1 + ----. each of the following five-digit integers are palindromes: 12321. on first glance.13 (Dangling-Else Problem) Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9.. } else { Console. b) if ( x < 10 ) { if ( y > 10 ) Console. 5! = 5 · 4 · 3 · 2 · 1. When the user dismisses the error dialog. and swap the second digit with the fourth. Console. the C# compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). 4. All Rights Reserved.WriteLine( "*****" ).16 The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is defined as follows: n! = n · (n . Because.+ ----. They have asked you to write a program that will encrypt their data so that it may be transmitted more securely. For ex- ample. 45554 and 11611.WriteLine( "*****" ).1) · (n . For example.14 A palindrome is a number or a text phrase that reads the same backward as forward. which is 120. If the number is not five digits. We have eliminated the inden- tation from the following code to make the problem more challenging.202 Control Structures: Part 1 Chapter 4 4. else Console. display an error message dialog indicating the problem to the user. 7/13/01 . Inc. (Hint: Apply indentation con- ventions you have learned.2) · . Your appli- cation should read a four-digit integer entered by the user in an input dialog and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third. Console. Write an application that reads in a five-digit integer and determines whether or not it is a palindrome. } 4. allow the user to enter a new value. the programmer may not be sure which if an else matches. All of their data is transmitted as four-digit integers.) a) if ( x < 10 ) if ( y > 10 ) Console. but they are concerned that their phones may be tapped. a) Write an application that reads a nonnegative integer from an input dialog and computes and prints its factorial.WriteLine( "#####" ). Also.15 A company wants to transmit data over the telephone. Then print the encrypted integer.WriteLine( "#####" ).WriteLine( "$$$$$" ). Note that the compiler ignores the indentation in a C# program. Write a separate application that inputs an encrypted four-digit integer and decrypts it to form the original number.+ … 1! 2! 3! c) Write an application that computes the value of ex by using the formula: © Copyright 1992–2002 by Deitel & Associates.WriteLine( "$$$$$" )..+ ----. this is referred to as the “dangling-else” problem.

+ ---- 1! 2! 3! © Copyright 1992–2002 by Deitel & Associates.x x.+ … e = 1 + ---.Chapter 4 Control Structures: Part 1 203 2 3 x x. All Rights Reserved. 7/13/01 . Inc.+ ----.

• The manuscript is being copyedited by a professional copy editor in parallel with your reviews. spelling errors. grammatical errors. • Please return only marked pages to Deitel & Associates.Chapter 4 Control Structures: Part 1 211 [***Notes To Reviewers***] • Please mark your comments in place on a paper copy of the chapter. Inc. • Please feel free to send any lengthy additional comments by e-mail to cheryl. That person will probably find most typos. • Please check that there are no inconsistencies. We will not make significant adjustments to our writing style on a global scale. Please send us a short e-mail if you would like to make such a suggestion.yaeger@dei- tel. • Please run all the code examples. • Please check that we are using the correct programming idioms. We all want to publish the best possible book. • Please be constructive. mark these directly on the pa- per pages. 7/13/01 . errors or omissions in the chapter discussions. • Please do not rewrite the manuscript. line-by-line comments. etc. • Please do not send us e-mails with detailed. • If you find something that is incorrect. All Rights Reserved. • Please read all of the back matter including the exercises and any solutions we provide.net. © Copyright 1992–2002 by Deitel & Associates. We are concerned mostly with technical correctness and cor- rect use of idiom. • Please review the index we provide with each chapter to be sure we have covered the topics you feel are important. Inc. This book will be published soon. please show us how to correct it.

176 double-selection structure 159. factorial 202 += (addition assignment operator) 191 false 161 183 fatal logic error 166 = (assignment operator) 183 connector symbol 159 control structure 158. 166. 161 computing 162 201 flowcharting the double-selection action/decision model of csc 170 if/else structure 163 programming 161 flowcharting the single-selection addition assignment operator (+=) if structure 162 183 D flowcharting the while repetition algorithm 156. 178 A control-structure stacking 160 flag value 171 abbreviating assignment counter 168.Add method 189 184 control-structure nesting 160 first refinement 171. 176 IEEE 754 floating-point 192 braces ({ and }) 165.) 166 indentation 160 char primitive data type 192 encrypt 202 indentation convention 162 checkerboard 209 end of data entry 171 infinite loop 166. 191 Controls.NET 184 for repetition structure 159 190 decimal primitive data type 192 foreach repitition structure 159 assignment operator (=) 183 decision 161 fractional result 176 associate left to right 191 decision symbol 159. 176 class average 168 examination-results problem 180 initialization at the beginning of class Int32 170 exit point of one control structure each repetition 182 coercion 177 160 initialization phase 173 © Copyright 1992–2002 by Deitel & Associates. 176 empty statement (. floating-point number 174 action symbol 159 175 flow of control 167. if selection structure 159. 175 action/decision model of credit limit on a charge account flowchart 158. statement 165 drawString 209 161. 161 braces that delimit a compound 179 if/else selection structure 159. All Rights Reserved. 179 building blocks 156 dummy value 171 if/else structure 174 byte primitive data type 192 dynamic memory allocation implicit conversion 177 operator 189 increment and decrement operators 185 C increment operator (++) 183 case-sensitive language 167 E indefinite repetition 171 cast operator 174. 172 float primitive data type 192 expressions 183 counter-controlled loop 178 floating-point division 177 action 156 counter-controlled repetition 168. C.NET ?: (ternary conditional) 162. 161 FromString method 176 associate right to left 177. 168 dangling-else problem 164. 7/13/01 . 170 decrypt 202 ”goto elimination” 158 default primitive data type 192 goto statement 158 default value 192 “goto-less programming” 158 B definite repetition 168 graphical representation of an binary arithmetic operator 177 design support 189 algorithm 158 "binary" integer 209 diamond 159. Inc. 202 structure 167 application class definition 170 Debug menu in Visual flowline 158 Application.Run method Studio. 167 block 166 division by zero 173 Bohm. 192 double 174. 167 gross pay 207 blank line 173 diamond symbol 159. 158 do/while repetition structure I bool primitive data type 161. 191 declaration 166 associativity of the operators 190 decrement operator (--) 183 average 171 decrement operators 185 G average calculation 168.Index 1 Symbols commission 206 explicit conversion 176 (type) (cast operator) 177 compound statement 165. 160 File menu in Visual Studio. 159 identifier 159 162. 161. 176 ++ (unary preincrement/ conditional expression 162 F postincrement) 183 conditional operator (?:) 162.

179 postdecrement operator 183 selection 160 K postdecrementing 183 selection structure 158. 190 short primitive data type 192 loop 171 preincrementing 184 signal value 171 looping 179 primitive (or built-in) data type single-entry/single-exit control lowercase letters 167 191 structures 160 lvalue ("left value") 190 procedure 156 single-entry/single-exit structure processing phase 173 161 program control 157 single-selection structure 159 M program development tools 182 small circle symbol 158. 158 screen 169 postdecrement 185 second refinement 172.Form new operator 189 pseudocode statement 166 class 188 © Copyright 1992–2002 by Deitel & Associates.NET pseudocode if/else structure 188 184 162 System.2 Index initialize 189 nonfatal logic error 166 R initialize counters and totals 169 real number 174 InitializeComponent method 184. 160. / and counter-controlled repetition strongly typed languages 191 % 177 to solve the class-average structured programming 158 problem 168 <summary> tag 188 N Pseudocode algorithm that uses switch selection structure 159 nest 179 sentinel-controlled syntax error 166. 159 keyboard 169. operator 174 166. 175. 165 Pseudocode for examination.Double 174 164. 172 int primitive data type operator precedence chart 177 174. 7/13/01 . 173 long primitive data type 192 preincrement operator 183. System. 173.Forms. 190 semicolon (.FromString method “rise-and-shine algorithm” 157 176 round 177 integer division 176 P paint method 209 S palindrome 202 J sbyte primitive data type 192 pay 207 Jacopini G. main form 190 promote 177 160 Main method 170 prompt 176 Solution Explorer in Visual maximum 207 Properties window in Visual Studio. System namespace 170 nested if/else structure 163.NET 184 mileage obtained by automobiles Studio. 189 O rectangle 158 object primitive data type 192 rectangle symbol 159.Win- nesting 162 results problem 180 dows.) 166 keyword 159 postincrementing 184 sentinel value 171.Form class New menu in Visual Studio.WinForms. precedence 190 172. 171.NET 184 stacking 162 201 pseudocode 157. 172 level of refinement 173 predecrement operator 183 sequential execution 157 local variable 170 predecrementing 183 shopping list 166 logic error 166. 176 power of 2 larger than 1000 167 sentinel-controlled repetition 171. 185 right brace (}) 170. 157 Int32 170 right triangle 210 oval symbol 159 Int32. 159. 175 order 156. 167 nested control structures 178 repetition to solve the class. 159. average problem 173 System. 167 input/output operation 159 “reinvent the wheel” 188 instantiating an object 189 operand 176 int primitive data type 192 repetition structure 158. 166 straight-time 207 modulus operator (%) 209 stream of input 171 pseudocode algorithm 173 multiple-selection list 159 pseudocode algorithm that uses string primitive data type 192 multiplicative operators: *. 161. Inc. 172 postincrement operator 183. 176 L precedence chart 177 largest value 207 sequence 160 predecrement 185 sequence structure 158. All Rights Reserved.

172 transfer of control 158 triangle 210 true 161 truncate 176 two largest values 207 U uint primitive data type 192 ulong primitive data type 192 unary cast operator 176 unary decrement operator (--) 183 unary operator 177 unary preincrement/postincrement operator (++) 183 Unicode 192 uninitialized local variables 170 ushort primitive data type 192 V vertical spacing 161 View menu in Visual Studio. 174. 175 while repetition struc- ture 166 while structure 167 white-space 161 Windows Application 184 © Copyright 1992–2002 by Deitel & Associates.NET 184 top 171. All Rights Reserved.NET 184 Visual C# Projects 184 W while repetition structure 155. 159. 178 top-down. 7/13/01 .Index 3 T temporary 176 termination phase 173 ternary operator (?:) 162 this reference 189 time-and-a-half 207 Toolbox window in Visual Studio. 178 total 168. 170. Inc. stepwise refinement 171. 173.