You are on page 1of 45

5

Control Structures:
Part 2

Objectives
• To be able to use the for and do/while repetition
structures to execute statements in a program
repeatedly.
• To understand multiple selection using the switch
selection structure.
• To be able to use the break and continue
program control statements.
• To be able to use the logical operators.
Who can control his fate?
William Shakespeare, Othello
The used key is always bright.
Benjamin Franklin
Man is a tool-making animal.
Benjamin Franklin
Intelligence . . . is the faculty of making artificial objects,
especially tools to make tools.
Henri Bergson

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

220 Control Structures: Part 2 Chapter 5

Outline
5.1 Introduction
5.2 Essentials of Counter-Controlled Repetition
5.3 The for Repetition Structure
5.4 Examples Using the for Structure
5.5 The switch Multiple-Selection Structure
5.6 do/while Repetition Structure
5.7 The break and continue Statements
5.8 Logical Operators
5.9 Structured Programming Summary
Summary • Terminology • Self-Review Exercises • Answers to Self-Review Exercises • Exercises

5.1 Introduction
Before writing a program to solve a particular problem, it is essential to have a thorough
understanding of the problem and a carefully planned approach to solving the problem.
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 we
discuss all of these issues in our presentation of the theory and principles of structured pro-
gramming. The techniques that you will learn here are applicable to most high-level lan-
guages, including C#. When we begin our formal treatment of object-based programming
in C# in Chapter 8, we will see that the control structures we study here in Chapter 5 are
helpful in building and manipulating objects.

5.2 Essentials of Counter-Controlled Repetition
Counter-controlled repetition requires:
1. The name of a control variable (or loop counter).
2. The initial value of the control variable.
3. The increment (or decrement) by which the control variable is modified each time
through the loop (also known as each iteration of the loop).
4. The condition that tests for the final value of the control variable (i.e., whether
looping should continue).
To see the four elements of counter-controlled repetition, consider the simple applica-
tion shown in Fig. 5.1, which displays the digits 1–5.
The declaration at line 10

int counter = 1;

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

Chapter 5 Control Structures: Part 2 221

names the control variable (counter), declares it to be an integer, reserves space for it in
memory and sets it to an initial value of 1. Declarations that include initialization are, in
effect, executable statements.
The declaration and initialization of counter could also have been accomplished
with the declaration and statement

int counter; // declare counter
counter = 1; // initialize counter to 1

The declaration is not executable, but the assignment statement is. We use both methods of
initializing variables throughout the book.
Lines 12–16 define our while structure. Line 14 displays the current value of counter,
and line 15 increments the control variable by 1 each iteration of the loop (i.e., each time
the body of the loop is performed). The loop-continuation condition in the while structure
tests if the value of the control variable is less than or equal to 5 (the final value for which
the condition is true). Note that the body of this while is performed even when the con-
trol variable is 5. The loop terminates when the control variable exceeds 5 (i.e., counter
becomes 6).

1 // Fig. 5.1: WhileCounter.cs
2 // Counter-controlled repetition.
3
4 using System;
5
6 class WhileCounter
7 {
8 static void Main( string[] args )
9 {
10 int counter = 1; // initialization
11
12 while ( counter <= 5 ) // repetition condition
13 {
14 Console.WriteLine( counter );
15 counter++; // increment
16 }
17 }
18 }

1
2
3
4
5

Fig. 5.1 Counter-controlled repetition.

The program in Fig. 5.1 can be made more concise by initializing counter to 0 and
by replacing the while structure with

while ( ++counter <= 5 ) // repetition condition

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

222 Control Structures: Part 2 Chapter 5

Console.WriteLine( counter );

This code saves a statement (and eliminates the need for braces around the loop’s body)
because the incrementing is done directly in the while condition before the condition is
tested (remember that the precedence of ++ is higher than <=). Coding in such a condensed
fashion takes practice.
Good Programming Practice 5.1
Control counting loops with integer values. 5.1

Common Programming Error 5.1
Because floating-point values may be approximate, controlling counting loops with floating-
point variables may result in imprecise counter values and inaccurate tests for termination. 5.1

Good Programming Practice 5.2
Indent the statements in the body of each control structure. 5.2

Good Programming Practice 5.3
Put a blank line before and after each major control structure to make it stand out in the pro-
gram. 5.3

Good Programming Practice 5.4
Too many levels of nesting can make a program difficult to understand. As a general rule, try
to avoid using more than three levels of nesting. 5.4

Good Programming Practice 5.5
Vertical spacing above and below control structures, and indentation of the bodies of control
structures within the control structure headers gives programs a two-dimensional appear-
ance that enhances readability. 5.5

5.3 The for Repetition Structure
The for repetition structure handles all the details of counter-controlled repetition. To il-
lustrate the power of for, let us rewrite the application of Fig. 5.1. The result is shown in
Fig. 5.2.

1 // Fig. 5.2: ForCounter.cs
2 // Counter-controlled repetition with the for structure.
3
4 using System;
5
6 class ForCounter
7 {
8 static void Main( string[] args )
9 {
10 // Initialization, repetition condition and incrementing
11 // are all included in the for structure
Fig. 5.2 Counter-controlled repetition with the for structure. (part 1 of 2)

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

Next.WriteLine( counter ). Because the control variable is now equal to 2. If the pro- grammer incorrectly wrote counter < 5. the control variable counter is initialized to 1 (the first two ele- ments of counter-controlled repetition—control variable name and initial value). 5. performs the next iteration of the loop). Notice that Fig. If there is more than one statement in the body of the for. All Rights Reserved. Notice that the for structure “does it all”—it spec- ifies each of the items needed for counter-controlled repetition with a control variable. Note that counter is declared inside the for and thus is known only in the for structure’s body. so the program performs the body statement again (i. (part 2 of 2) The Main method of the application operates as follows. true). When the for structure (line 12) begins executing.2 Counter-controlled repetition with the for structure. 5. 7/18/01 . the loop would be only executed nine times. 5.e. the loop-continuation condition counter <= 5 is checked. 14 } 15 } 1 2 3 4 5 Fig.2. and the loop begins again with the loop-continuation test. Inc. Because the initial value of counter is 1. Variable counter is then incremented in the expression counter++. This process continues until the control variable counter is incremented to 6—this causes the loop-continuation test to fail and repetition terminates. the final value is not exceeded. The first line of the for structure (including the keyword for and everything in parentheses after for) is some- times called the for structure header.3 takes a closer look at the for structure in Fig.2 uses the loop-continuation condition counter <= 5. The condition contains the final value (5) of the control variable. the condition is satisfied (i. This is a common logic error called an off-by-one error. method Main terminates because the end of its body is reached). so the body statement (line 13) outputs the value of counter. braces ({ and }) are required to define the body of the loop.. © Copyright 1992–2002 by Deitel & Associates. counter <= 5.3 Components of a typical for header.e. Figure 5. The program continues by performing the first statement after the for structure (in this case.. counter <= 5. Chapter 5 Control Structures: Part 2 223 12 for ( int counter = 1. counter++ ) 13 Console. for keyword Control variable name Final value of control variable for ( int counter = 1. counter++ ) Initial value of control variable Increment of control variable Loop-continuation condition Fig. 5.

This restricted use of the control vari- able name is known as the variable’s scope. for or do/while structure can cause an off-by-one error.3 Sometimes. 5. All Rights Reserved.. 7/18/01 . expression2 and expression3 placed as follows: expression1. 5.6 Using the final value in the condition of a while or for structure and using the <= rela- tional operator will help avoid off-by-one errors.6 The general format of the for structure is for ( expression1. } There is an exception to this rule that we will discuss in Section 5. in which to count 10 times through the loop. expression2. 5. while ( expression2 ) { statement expression3. The scope of a variable defines where it can be used in a program. For example. the control variable’s type is specified before the variable name). expression2 is the loop-continuation condition (containing the control variable’s final val- ue) and expression3 increments the control variable.” Common Programming Error 5. counter would be initialized to zero and the loop-continuation test would be counter < 10. there may be several control variables in a single for structure that must be initialized and incremented.2 Good Programming Practice 5. for example.. the value of the control variable will be unknown outside the for structure). For a loop used to print the values 1 to 10. expression3 ) statement where expression1 names the loop’s control variable and provides its initial value.e. the con- trol variable can only be used in the body of the for structure (i. © Copyright 1992–2002 by Deitel & Associates.3 When the control variable of a for structure is initially defined in the initialization section of the for structure header.224 Control Structures: Part 2 Chapter 5 Common Programming Error 5. expression1 and expression3 in a for structure are comma-separated lists of expressions that enable the programmer to use multiple initialization expressions and/or multiple increment expressions. “Methods. Inc. Scope is discussed in detail in Chapter 6. In most cases the for structure can be represented with an equivalent while structure with expression1.2 Using an incorrect relational operator or using an incorrect final value of a loop counter in the condition of a while.e. If expression1 (the initialization section) in the for structure header defines the con- trol variable (i. Many programmers prefer so-called zero-based counting.7. the loop-continuation condition should be counter <= 10 rather than counter < 10 (which is an off-by-one error) or counter < 11 (which is correct). using the control variable after the body of the structure is a syntax error.

Manipulations of other variables should appear either before the loop (if they execute only once. Because the variable be- ing incremented here does not appear in an expression.7 Place only expressions involving the control variables in the initialization and increment sec- tions of a for structure. for example.” we introduce a much better technique for introducing delays into programs. The increment expression in the for struc- ture acts like a stand-alone statement at the end of the body of the for.1 The initialization. assume that x = 2 and y = 10.4 Using commas instead of the two required semicolons in a for header is a syntax error. 5. 7/18/01 . Therefore. One might omit expression3 if the increment is calculated by statements in the body of the for or if no increment is needed. preincrementing and postincrementing have the same effect. C# assumes that the loop-continuation condition is true. Inc. like incrementing or decrementing statements). loop-continuation condition and increment portions of a for struc- ture can contain arithmetic expressions. thus creating an infinite loop. Common Programming Error 5. like initialization statements) or in the loop body (if they ex- ecute once per iteration of the loop. the statement for ( int j = x.5 Placing a semicolon immediately to the right of the right parenthesis of a for header makes the body of that for structure an empty statement. “Multithreading. Many programmers prefer the form counter++ because the control variable increment occurs after the loop body is ex- ecuted. [In Chap- ter 14. If x and y are not modified in the loop body.7 The three expressions in the for structure are optional.Chapter 5 Control Structures: Part 2 225 Good Programming Practice 5. The postincrementing form therefore seems more natural. If expression2 is omitted. For example. 5. so you should never use delay loops.5 Software Engineering Observation 5. One might omit expression1 if the control variable is initialized elsewhere in the program before the loop. All Rights Reserved. j <= 4 * x * y. 5.1 Placing a semicolon immediately after a for header is sometimes used to create a so-called delay loop.4 Common Programming Error 5. j += 5 ) © Copyright 1992–2002 by Deitel & Associates. the expressions counter = counter + 1 counter += 1 ++counter counter++ are equivalent in the increment portion of the for structure. j <= 80. j += y / x ) is equivalent to the statement for ( int j = 2.] 5. to slow down a program that is producing outputs on the screen too quickly for you to read them. This is normally a logic error. You might use a delay loop. Such a for loop with an empty body still loops the indicated number of times doing nothing other than the counting. The two semicolons in the for structure are re- quired.

that the programmer has access to a deep bin of empty for structures—as many as the programmer might need to stack and nest with other control structures to form a structured implementation of an algorithm’s flow of control. Note that (besides small circles and arrows) the flowchart contains only rectangle symbols and a di- amond symbol. Establish initial value int counter = 1 of control variable. again. The control variable is frequently printed or used in calculations in the body of a for structure. counter++ ) Console. The rect- angles and diamonds are then filled with actions and decisions appropriate to the algorithm. the flowchart of the for statement for ( int counter = 1. 7/18/01 . © Copyright 1992–2002 by Deitel & Associates. In each case. Determine if final Console. Instead. 5. If the loop-continuation condition is initially false. (this may be many statements) Fig. Testing and Debugging Tip 5. All Rights Reserved. avoid doing so because this practice can lead to subtle errors. 5. reached.WriteL value of control true ine( counter * counter <= 10 counter++ variable has been 10 ).WriteLine( counter * 10 ). we write the appropriate for header.4 Flowcharting a typical for repetition structure. counter <= 10.1 The for structure is flowcharted much like the while structure. 5. Inc. the body of the for structure is not performed. execution proceeds with the statement following the for structure. Imagine. For example. Note the change in the relational oper- ator for loops that decrement the control variable.1 Although the value of the control variable can be changed in the body of a for loop. is shown in Fig. This flowchart makes it clear that the initialization occurs only once and that incrementing occurs each time after the body statement is performed. in which case it is really a dec- rement and the loop actually counts downward. 5. but it does not have to be. a) Vary the control variable from 1 to 100 in increments of 1. Increment the control false Body of loop variable.4 Examples Using the for Structure The following examples show methods of varying the control variable in a for structure.4.226 Control Structures: Part 2 Chapter 5 The “increment” of a for structure may be negative. It is common to use the control variable for controlling repetition while never mentioning it in the body of the for structure.

) Common Programming Error 5. i >= 1. i <= 100. for ( int i = 100. number += 2 ) 14 sum += number. Chapter 5 Control Structures: Part 2 227 for ( int i = 1.Windows.5: Sum. 5.5 uses the for structure to sum all the even integers from 2 to 100. for ( int i = 20. Fig. 5.5 Summation using for. 0. All Rights Reserved. for ( int j = 2. i++ ) b) Vary the control variable from 100 to 1 in increments of -1 (decrements of 1). for ( int i = 7. 88. for ( int j = 99. 12 13 for ( int number = 2. i >= 2. 11. j >= 0. 33. 44. 22. j -= 11 ) The next two sample programs demonstrate simple applications of the for repetition structure. i-. 17 "Sum Even Integers from 2 to 100". number <= 100. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates. j <= 20. i += 7 ) d) Vary the control variable from 20 to 2 in steps of -2. 77. i <= 77.6 c) Vary the control variable from 7 to 77 in steps of 7.dll manually as was explained in Chapter 3.Forms. The application of Fig. 66. 14. Remember that the C# compiler is used to execute an application from the command window.Windows. 7/18/01 . 8. 1 // Fig 5. j += 3 ) f) Vary the control variable over the following sequence of values: 99. 55. 3 4 using System.Show( "The sum is " + sum. 5. i -= 2 ) e) Vary the control variable over the following sequence of values: 2.Forms. 6 7 class Sum 8 { 9 static void Main( string[] args ) 10 { 11 int sum = 0. 11.cs 2 // Summation with the for structure. 17.6 Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (such as using i <= 1 in a loop counting down to 1) is usually a logic error that will yield incorrect results when the program runs. 15 16 MessageBox. 5 using System. Inc. 20. 5. It is important to remember that a reference must be added to System.

5.Information ). 228 Control Structures: Part 2 Chapter 5 18 MessageBoxButtons. All Rights Reserved. The message dialog icons are described in Fig. number <= 100.Show used in Fig. 7/18/01 . the first argument will always be the message to display.NET includes the complete listing of Message- BoxButtons and MessageBoxIcon choices. The MSDN doc- umentation provided with Visual Studio. The version of method MessageBox. Argument 4: The MessageBox Icon Argument 2: The title bar string Argument 1: The Arugument 3: The message to display OK dialog button. 5.5 Summation using for.6. sum += number. (part 2 of 2) Note that the body of the for structure in Fig. number += 2). As with the first version. The fourth argument allows the user to display a specific dialog icon to the left of the message. 5. Inc. 19 MessageBoxIcon.OK. 5.5 could actually be merged into the rightmost portion of the for header by using a comma as follows: for ( int number = 2. Similarly. 20 } 21 } Fig. The second argument is the string which will be displayed in the title bar of the dialog. The third argument is a value indi- cating the button or buttons that will be displayed for user interaction. © Copyright 1992–2002 by Deitel & Associates.5 (lines 16–19) is dif- ferent from the one discussed in earlier examples because it requires four arguments instead of one. the initialization sum = 0 could be merged into the initialization section of the for structure. The following dialog box illustrates the four arguments.

Helps alert user of errors or important messages. The solution is the application shown in Fig.7. Fig. MessageBoxIcon. MessageBoxIcon.6 Icons for message dialogs.8 Good Programming Practice 5. This problem involves a loop that performs the indicated calculation for each of the 10 years the money remains on deposit.00 in a savings account yielding 5% interest.9 Limit the size of control structure headers to a single line if possible.Information Displays a dialog with an informa- tional message to the application user. © Copyright 1992–2002 by Deitel & Associates. 5.Exclamation Displays a dialog with an exclamation point.9 The next example computes compound interest using the for structure. calculate and print the amount of money in the account at the end of each year for 10 years.Error Displays a dialog with a red stop sign.e. Good Programming Practice 5. Typically used to ask the user a question. Use the following formula for determining these amounts: a = p (1 + r) n where p is the original amount invested (i. 5. All Rights Reserved. 5. Consider the following problem statement: A person invests $1000. These messages can usually be dis- missed by the user.. the principal) r is the annual interest rate n is the number of years a is the amount on deposit at the end of the nth year.Chapter 5 Control Structures: Part 2 229 MessageBox Icons Icon Description MessageBoxIcon. 5. Assuming that all interest is left on deposit. Inc.8 Although statements preceding a for and statements in the body of a for can often be merged into the for header.Question Displays a dialog that a question mark. 7/18/01 . Typically used for warnings or potential problems. MessageBoxIcon. avoid doing so because it makes the program more difficult to read.

230 Control Structures: Part 2 Chapter 5 1 // Fig 5.Windows. 12 13 string output. MessageBoxIcon.0 and rate to . 22 } 23 24 MessageBox.Forms. 14 15 output = "Year\tAmount on deposit\n". All Rights Reserved. 26 } 27 } Fig. 25 MessageBoxButtons. C# does not include an exponentiation operator.7: Interest.OK. year <= 10. year ). Inc. "Compound Interest".0 + rate. Line 11 in method Main declares three double variables and initializes prin- cipal to 1000.Information ).0. The for structure executes its body 10 times.cs 2 // Calculating compound interest. Math. we use static method Pow in class Math for this purpose.Format( amount. varying control variable year from 1 to 10 in increments of 1 (note that year represents n in the problem statement). 7/18/01 . 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 double amount.Show( output. 5 using System. Instead. rate = . y ) calculates the value of x raised to the yth © Copyright 1992–2002 by Deitel & Associates.00" ) + "\n". 3 4 using System.Pow( x. year++ ) 18 { 19 amount = principal * Math. principal = 1000. 5.05. 21 "0. 16 17 for ( int year = 1.Pow( 1. 20 output += year + "\t" + Double.7 Calculating compound interest with for.05.

MessageBoxIcon.67 for display purposes). many of today’s sophisticated optimizing compilers will automatically place such expressions out- side loops in the generated machine-language code.7 are treated as type double by C#. Line 19 performs the calculation from the problem statement n a = p (1 + r) where a is amount. which formats the amount with two digits to the right of the decimal point. Inc. Lines 24–25 MessageBox.23 + 18. Constants like 1000. In the exercises.] 5.00" ). p is principal.1 Avoid placing expressions whose values do not change inside loops.90! You have been warned! Good Programming Practice 5. which would normally be rounded to 32. In fact. this calculation produces the same result each time through the loop.673 (which would normally be rounded to 18.91 but a person adding the individual numbers as printed would expect the sum 32.Show( output.234 (which would normally be rounded to 14. "Compound Interest". principal and rate are of type double.67 ------- 32. 7/18/01 .0 + rate that appears as an argument to the Math.23 for display purposes) and 18. But even if you do. MessageBoxButtons. All Rights Reserved.Chapter 5 Control Structures: Part 2 231 power. 5. When these amounts are added.Pow takes two arguments of type double and returns a double value. r is rate and n is year in line 19. we explore the use of integers to perform monetary calcula- tions.0 and . 5. use static method MessageBox. [Note: Class Decimal is available for properly performing monetary calculations. The imprecision of floating-point numbers can cause errors that will result in incorrect mon- etary values. so repeating the calculation is wasteful.05 in Fig. Performance Tip 5.Show to display the results in a message dialog. they produce the internal sum 32. Method Math. Here is a simple explanation of what can go wrong when using float or double to represent dollar amounts (assuming that dollar amounts are displayed with two digits to the right of the decimal point): Two double dollar amounts stored in the machine could be 14. and a newline character (to position the cursor at the beginning of the next line).Pow method is contained in the body of the for statement.OK.91 for display purposes. Notice that the variables amount. this can cause trouble.10 Note that the calculation 1. "0. The text includes the current year value. We did this for simplicity because we are dealing with fractional parts of dollars and we need a type that allows decimal points in its values. a tab character (to position to the second column).Format( amount.907. Unfortunately. Thus your printout could appear as 14.10 Do not use variables of type float or double to perform precise monetary calculations. the result of the method call Double.Information ). Lines 20–21 appends more text to the end of the string output.1 © Copyright 1992–2002 by Deitel & Associates.

5. an algorithm will contain a series of decisions in which a variable or expression is tested separately for each of the constant integral values (i.2 Many compilers contain optimization features that improve the code you write. C# provides the switch multiple-selection structure to handle such decision making. short. and different actions are tak- en. 20 grade = Console.ReadLine(). Occasionally. 28 29 case 'B': // grade was uppercase B 30 case 'b': // or lowercase b 31 ++bCount. 21 22 switch ( grade ) 23 { 24 case 'A': // grade was uppercase A 25 case 'a': // or lowercase a 26 ++aCount.cs 2 // Counting letter grades. 5. 7/18/01 .5 The switch Multiple-Selection Structure We have discussed the if single-selection structure and the if/else double-selection structure. int. Line 10 in Fig. long and char) it may assume.8 defines instance variable grade of type int. 232 Control Structures: Part 2 Chapter 5 Performance Tip 5. 1 // Fig. 5. values of types byte.2 5. All Rights Reserved.Write( "Enter a letter grade: " ). Inc.8 An example using switch. // number of A's 12 bCount = 0. 3 4 using System.8 demonstrates adding up letter grades. // number of D's 15 fCount = 0. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates.8: SwitchTest.ToChar(). The application of Fig. // number of C's 14 dCount = 0.e. 5.. 33 34 case 'C': // grade was uppercase C Fig. i++ ) 18 { 19 Console. 5. // one grade 11 aCount = 0. 27 break. i <= 10. // number of F's 16 17 for ( int i = 1. 5 6 class SwitchTest 7 { 8 static void Main( string[] args ) 9 { 10 int grade. 32 break. but it is still better to write good code from the start. This variable will store the user’s input that determines a student’s grade. // number of B's 13 cCount = 0.

38 39 case 'D': // grade was uppercase D 40 case 'd': // or lowercase d 41 ++dCount. 61 cCount. 54 break. 53 i--. 5. 7/18/01 . All Rights Reserved. 48 49 default: // catch all other characters 50 Console. aCount. Enter a new grade Enter a letter grade: D Enter a letter grade: d Enter a letter grade: B Enter a letter grade: a Enter a letter grade: C Enter a letter grade: C Totals for each letter grade are: A: 3 B: 1 C: 3 D: 2 F: 1 Fig. 37 break. bCount.WriteLine( 59 "\nTotals for each letter grade are:\nA: {0}" + 60 "\nB: {1}\nC: {2}\nD: {3}\nF: {4}". //optional 55 } 56 } 57 58 Console. 62 } 63 } Enter a letter grade: a Enter a letter grade: A Enter a letter grade: c Enter a letter grade: F Enter a letter grade: z Incorrect letter grade entered. fCount ).WriteLine( 51 "Incorrect letter grade entered.8 An example using switch. Chapter 5 Control Structures: Part 2 233 35 case 'c': // or lowercase c 36 ++cCount. 42 break." + 52 "\nEnter a new grade" ). 47 break. Inc. dCount. (part 2 of 2) © Copyright 1992–2002 by Deitel & Associates. 43 44 case 'F': // grade was uppercase F 45 case 'f': // or lowercase f 46 ++fCount.

flowchart the general switch structure without breaks. The break statement is used because the cases in a switch statement would otherwise run together.] © Copyright 1992–2002 by Deitel & Associates. 9 and 10. If break is not used anywhere in a switch structure. the default case executes and an error message is displayed using a message dialog. 8. The value of this expression (which must evaluate to an integral value of type byte. The switch structure is different from other structures in that braces are not required around multiple actions in a case of a switch. The values of i for the 10 iterations of the loop are 1. the controlling expression (grade in this example) in the parentheses following keyword switch is evaluated. so control flows to the control variable’s increment expression in the for structure header). the statements for that case are executed. increment the number of B grades (or variable b). the statements for all the remaining cases will be executed. and then the switch structure exits im- mediately with the break statement.”) If no match occurs between the controlling expression’s value and a case label. char. Each case can have multiple actions. The counter variable in the for structure is then in- cremented and the loop-continuation condition is evaluated to determine if another iteration of the loop should be performed. break. 4.9. For the letter B. 2. Assume the user entered the letter B as the grade. and the loop terminates when i’s value becomes 11. B is compared to each case in the switch. If a match occurs (case ’B’:). Inc. Note that the for structure header at line 17 for ( int i = 1. 5. short or int) is compared with each case label.234 Control Structures: Part 2 Chapter 5 Line 17 begins a for structure that loops 10 times. 6. [Note: As an exercise. When the flow of control reaches the switch structure. (This feature is perfect for programming the iterative song “The Twelve Days of Christmas. i++ ) { uses zero-based counting in this example. i <= 10. The switch structure consists of a series of case labels and an optional default case. 3. The general switch structure (using a break in each case) is flowcharted in Fig. lines 31–32 ++bCount. then each time a match occurs in the structure. Nested in the body of the for structure is a switch structure (lines 22–55) handles the different letter grade inputs. All Rights Reserved. 5. 7. 7/18/01 . The break statement causes program control to proceed with the first statement after the switch structure (in this case we reach the end of the for structure’s body.

. 5.7 © Copyright 1992–2002 by Deitel & Associates. Common Programming Error 5.Chapter 5 Control Structures: Part 2 235 true case a case a action(s) break false true case b case b action(s) break false . 7/18/01 . . note that (besides small circles and arrows) the flowchart contains only rect- angle symbols and diamond symbols. 5. Although nested control structures are common.7 Forgetting a break statement when one is needed in a switch structure is a logic error. The break statement is not required for the last case in the switch structure (or the default case when it appears last) because the program automatically continues with the next statement after the switch. Inc. again. The flowchart makes it clear that each break statement at the end of a case causes control to immediately exit the switch structure. All Rights Reserved.9 switch multiple-selection structure. that the programmer has access to a deep bin of empty switch structures—as many as the programmer might need to stack and nest with other control structures to form a structured implementation of an algorithm’s flow of control. Again. true case z case z action(s) break false default action(s) Fig. Imagine. Again. it is rare to find nested switch structures in a program. the rectangles and diamonds are filled with actions and decisions appropriate to the algorithm.

a variable that contains a value that does not change for the entire program. Including a default case focuses the pro- grammer on the need to process exceptional conditions. (i. remember that the expression after each case can only be a constant integral expression. The do/while structure tests the loop-continuation condition af- ter the loop body is performed. Cases not explicitly tested in a switch statement without a default case are ignored.11 Good Programming Practice 5. the break for that case statement is not required. There are situations in which no default processing is needed. easier to maintain and easier to extend than programs using switch logic. the loop body is always executed at least once. “Methods”).236 Control Structures: Part 2 Chapter 5 Good Programming Practice 5. We will use a technique called polymorphism to create programs that are often clearer. such as 'A'.e. 7/18/01 . 5. the loop-continuation condition is tested at the beginning of the loop before the body of the loop is performed.. it is considered a good programming practice to place the default clause last. execution continues with the statement after the while clause. For example. Such a variable is declared with keyword const (discussed in Chapter 6. while ( condition ) is normally regarded as the header to a while structure. In the while struc- ture. Some programmers include this break for clarity and symmetry with other cases. Note that it is not necessary to use braces in the do/while structure if there is only one statement in the body. A do/while with no braces around the single statement body appears as do statement while ( condition ). therefore.6 do/while Repetition Structure The do/while repetition structure is similar to the while structure. any combination of character constants and integer constants that evaluates to a constant integer value). When a do/while terminates.e. While we discuss object-oriented programming in Chapter 10. The expression after each case can also be a constant variable—i. we will present a more elegant way to implement switch logic. A character constant is repre- sented as the specific character in single quotes. 5.13 In a switch structure. the braces are usually included to avoid confusion be- tween the while and do/while structures.. All Rights Reserved.12 Good Programming Practice 5.13 Note that listing case labels together (such as case 'C': case 'c': with no state- ments between the cases) performs the same set of actions to occur for each of the cases. When using the switch structure.12 Although the cases and the default case in a switch structure can occur in any order. However.11 Provide a default case in switch statements. © Copyright 1992–2002 by Deitel & Associates. 5. Inc. when the default clause is listed last. An integer constant is simply an integer value. 5.

3 4 using System. All Rights Reserved. the do/while with one statement is often written as follows to avoid confusion: do { statement } while ( condition ). 5 6 public class DoWhileLoop 7 { 8 public static void Main( string[] args ) 9 { 10 int counter = 1. make sure the control variable is incremented (or decremented) in the body of the loop. Inc.WriteLine( counter ). displaying the value of counter (at this point.10: Fig05_10. 17 } 18 } 1 2 3 4 5 Fig.10 Using the do/while repetition structure. make sure there is not a semicolon immediately after the header of a while or for structure. 5. 5.14 Some programmers always include braces in a do/while structure even if the braces are not necessary. In a counter-controlled loop. 5. Chapter 5 Control Structures: Part 2 237 which can be confusing. In a sentinel-controlled loop.—may be misinterpreted by the reader as a while structure containing an empty statement (the semicolon by itself). and then © Copyright 1992–2002 by Deitel & Associates. The last line—while( condition ). 15 counter++. This helps eliminate ambiguity between the while structure and the do/ while structure containing one statement. 5. 1). 1 // Fig. 7/18/01 . To prevent this. lines 14–15 are executed. make sure the sentinel value is eventually input.8 The application in Fig. 16 } while ( counter <= 5 ). 5. for or do/ while structure never becomes false. On lines 12–16 we see our first do/while structure. The first time we reach this struc- ture.14 Common Programming Error 5.cs 2 // The do/while repetition structure. 11 12 do 13 { 14 Console.8 Infinite loops are caused when the loop-continuation condition in a while. Good Programming Practice 5. Thus.10 uses a do/while structure to again output the values 1–5.

line 14 will output the value 5. and the do/while structure exits. The break statement. The do/while flowchart (Figure 5. 5. causes immediate exit from that structure. the condition on line 16 evaluates to false. The loop fully executes its body only four times. When the if structure at line 16 in the for structure detects that count is 5. 5. This terminates the for structure and the program proceeds to line 23 (imme- diately after the for). break is executed. 238 Control Structures: Part 2 Chapter 5 incrementing counter. 5. the condition on line 16 will be evaluated.12: BreakTest. The fifth time the structure is executed.12 demonstrates the break statement in a for repetition structure. do/while or switch structure. The flowchart contains only a rectangle and a diamond. and on line 15 counter will be incremented to 6. action(s) true condition false Fig. (part 1 of 2) © Copyright 1992–2002 by Deitel & Associates. that the programmer has access to a bin of empty do/while structures—as many as the programmer might need to stack and nest with other control structures to form a structured implementation of an algorithm. At this point. Variable counter is at this point 2 which is still less than or equal to 5. where the string concatenation statement produces the final string that is to be displayed in the message dialog on lines 25–26.cs 2 // Using the break statement in a for structure. Inc. and so the do/while struc- ture will execute again. 7/18/01 . Imagine. At this point. 3 Fig. when executed in a while.11) makes it clear that the loop-continuation con- dition is not executed until the action is performed at least once. The rect- angles and diamonds are filled with actions and decisions appropriate to the algorithm. Com- mon uses of the break statement are to escape early from a loop or to skip the remainder of a switch structure (as in Fig.8). Figure 5. Execution continues with the first statement after the structure. also. 1 // Fig 5.12 Using the break statement in a for structure.7 The break and continue Statements The break and continue statements alter the flow of control. for. 5. All Rights Reserved.11 Flowcharting the do/while repetition structure.

24 25 MessageBox.12 Using the break statement in a for structure.Show( output. 21 } 22 23 output += "\nBroke out of loop at count = " + count. the increment does not execute before the repeti- tion-continuation condition is tested. count++ ) 15 { 16 if ( count == 5 ) 17 break. the loop-continuation test is evalu- ated immediately after the continue statement is executed. and the while does not execute in the same manner as the for. skips the remaining statements in the body of that structure and proceeds with the next iter- ation of the loop. we stated that the while structure could be used in most cases to represent the for structure. when executed in a while.13 uses the continue statement in a for structure to skip the string concatenation statement at line 19 when the if structure at line 15 determines that the value of count is 5. Earlier. 12 int count. // skip remaining code in loop 18 // only if count == 5 19 20 output += count + " ". 6 7 class BreakTest 8 { 9 static void Main( string[] args ) 10 { 11 string output = "". MessageBoxButtons.OK. In the for structure. 13 14 for ( count = 1. the increment expression is executed.Information ).Forms. When the continue statement executes. In while and do/while structures. In this case. program control continues with the increment of the control variable in the for structure. 5. 26 MessageBoxIcon. for or do/while structure. © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. "". Chapter 5 Control Structures: Part 2 239 4 using System. count <= 10. 5 using System. 27 } 28 } Fig. (part 2 of 2) The continue statement. The one exception occurs when the increment expression in the while structure follows the continue statement. then the loop-continuation test is evaluated. Inc. 7/18/01 .Windows. Figure 5.

13 Using the continue statement in a for structure.15 Some programmers feel that break and continue violate structured programming.2 © Copyright 1992–2002 by Deitel & Associates. 5 using System. 6 7 class ContinueTest 8 { 9 static void Main( string[] args ) 10 { 11 string output = "". 3 4 using System.15 1 // Fig 5. Often. 20 } 21 22 output += "\nUsed continue to skip printing 5". Performance Tip 5. count++ ) 14 { 15 if ( count == 5 ) 16 continue. 12 13 for ( int count = 1.Information ). 25 MessageBoxIcon. perform faster than the cor- responding structured techniques. 5.OK. make your code simple and correct. these programmers do not use break and continue.Windows. count <= 10. "".3 The break and continue statements. All Rights Reserved. 26 } 27 } Fig. then make it fast and small. // skip remaining code in loop 17 // only if count == 5 18 19 output += count + " ". 7/18/01 . when used properly.2 There is a tension between achieving quality software engineering and achieving the best performing software. 5. 5. Inc.3 Software Engineering Observation 5.Show( output. 23 24 MessageBox. 5. Be- cause the effects of these statements can be achieved by structured programming techniques. 240 Control Structures: Part 2 Chapter 5 Good Programming Practice 5. only if necessary. For all but the most performance-intensive situations apply the following “rule of thumb”: First.13: ContinueTest. one of these goals is achieved at the expense of the other.cs 2 // Using the continue statement in a for structure.Forms. MessageBoxButtons.

|| (logical OR). C# evaluates to false or true all expressions that include rela- tional operators. The two simple conditions are evalu- ated first because the precedences of == and >= are both higher than the precedence of &&. To test multiple conditions in the process of making a decision.WriteLine( "Student grade is A" ). 7/18/01 . to determine if a person is a female. Inc. In this case we can use the logical && operator as follows: if ( gender == 1 && age >= 65 ) ++seniorFemales. also called logical negation). The condition finalExam >= 90 is evaluat- © Copyright 1992–2002 by Deitel & Associates.14 summarizes the && operator. The condition semesterAverage >= 90 is evaluated to determine if the student deserves an “A” in the course because of a solid performance throughout the semester. >= and <= and the equality operators == and !=. The preceding combined con- dition can be made more readable by adding redundant parentheses: ( gender == 1 ) && ( age >= 65 ) The table of Fig. if this combined condition is indeed true. We will consider examples of each of these. The logical operators are && (logical AND). In this case we use the || operator as in the following program segment: if ( semesterAverage >= 90 || finalExam >= 90 ) Console. The condition gender == 1 might be evaluated. we per- formed these tests in separate statements or in nested if or if/else structures.Chapter 5 Control Structures: Part 2 241 5. Finally. The table shows all four possible combinations of false and true values for expression1 and expression2. If either or both of the simple conditions are false. These conditions were expressed in terms of the relation- al operators >. equality operators and/or logical operators. Now let us consider the || (logical OR) operator. ^ (boolean logical exclusive OR) and ! (logical NOT. This statement also contains two simple conditions. Such tables are often called truth tables. C# provides logical operators that may be used to form more complex conditions by combining simple conditions. the program skips the increment- ing and proceeds to the statement following the if structure. <. Suppose we wish to ensure at some point in a program that two conditions are both true before we choose a certain path of execution. The if statement then considers the combined condition gender == 1 && age >= 65 This condition is true if and only if both of the simple conditions are true. 5. All Rights Reserved. Suppose we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. for example. This if statement contains two simple conditions. The condition age >= 65 is evaluated to determine if a person is a senior citizen. & (boolean log- ical AND). the count of seniorFemales is incremented by 1. Each decision tested one condition.8 Logical Operators So far we have studied only simple conditions such as count <= 10. total > 1000 and number != sentinelValue. | (boolean logical inclusive OR).

14 Truth table for the && (logical AND) operator . and continue if gender is equal to 1 (i.242 Control Structures: Part 2 Chapter 5 ed to determine if the student deserves an “A” in the course because of an outstanding per- formance on the final exam.15 is a truth table for the logical OR operator (||). expression1 expression2 expression1 || expression2 false false false false true true true false true true true true Fig. Both operators asso- ciate from left to right. All Rights Reserved.9 © Copyright 1992–2002 by Deitel & Associates. In this case.e. 5. the entire expression could still be true if the condition age >= 65 is true). 5. The if statement then considers the combined condition semesterAverage >= 90 || finalExam >= 90 and awards the student an “A” if either or both of the simple conditions are true.15 Truth table for the || (logical OR) operator . the dependent condition should be placed after the other condition or an error might occur. it is possible that a condition—we will call this the depen- dent condition—may require another condition to be true for it to be meaningful to evalu- ate the dependent condition. This performance feature for evaluation of logical AND and logical OR expressions is called short-circuit evaluation. Inc. Thus. The && operator has a higher precedence than the || operator.e... evaluation of the expression gender == 1 && age >= 65 expression1 expression2 expression1 && expression2 false false false false true false true false false true true true Fig. will stop immediately if gender is not equal to 1 (i. Common Programming Error 5. 5. Fig. 7/18/01 . 5. An expression containing && or || operators is evaluated only until truth or falsity is known. Note that the message “Student grade is A” is not printed only when both of the simple condi- tions are false.9 In expressions using operator &&. the entire expression is false).

4 The boolean logical AND (&) and boolean logical inclusive OR (|) operators. For example. 5. make the condition that is most likely to be false the leftmost condition. the result of the entire condition is false. such as in the following program segment: if ( ! ( grade == sentinelValue ) ) Console.Chapter 5 Control Structures: Part 2 243 Performance Tip 5.e. Unlike the logical operators &&. avoid expressions with side effects in conditions. the logical negation operator has only a single condition as an operand (unary operator). make the condition that is most likely to be true the leftmost condition. Thus. The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation oper- ator) is false.WriteLine( "The next grade is " + grade ).16 A condition containing the boolean logical exclusive OR (^) operator is true if and only if one of its operands results in a true value and one results in a false value. In expressions us- ing operator ||.16 is a truth table for the logical exclusive OR operator (^). if the separate conditions are independent of one another. Figure 5. the expression birthday == true | ++age >= 65 guarantees that the condition ++age >= 65 will be evaluated.16 For clarity. All Rights Reserved. the variable age will be incremented in the preceding expression regardless of whether the overall expression is true or false. there is no short-circuit evaluation).e. the expression gender == 1 & age >= 65 evaluates age >= 65 regardless of whether gender is equal to 1. This is useful if the right operand of the logical AND or logical inclusive OR operator has a needed side effect—a modification of a variable’s value. Inc. If both operands are true or both are false. This can reduce a program’s execution time.16 Truth table for the boolean logical exclusive OR (^) operator (part 1 of 2). C# provides the! (logical negation) operator to enable a programmer to “reverse” the meaning of a condition. Good Programming Practice 5. 7/18/01 . 5. expression1 expression2 expression1 ^ expression2 false false false false true true Fig. but they are often more trouble than they are worth. This operator is also guaranteed to evaluate both of its operands (i.4 In expressions using operator &&.. © Copyright 1992–2002 by Deitel & Associates. | and ^ which combine two conditions (binary operators). &. ||. Therefore. The side effects may look clever. work identically to the regular logical AND and logical OR operators with one exception—the logical operators always evaluate both of their operands (i. 5. there is no short-circuit eval- uation)..

This flexibility can help a programmer express a condition in a more convenient manner.18 Demonstrating the logical operators (part 1 of 4) © Copyright 1992–2002 by Deitel & Associates. Notice that by default. For example.18 demonstrates all the logical operators and boolean logical operators by producing their truth tables. two &’s are needed.17 Truth table for operator! (logical NOT) . Note that when you add a bool value to a string. this class is called Form1. Notice also that the title bar of the form contains the name of the class (LogicalOperators) by default. 5. |. The result of the condition is shown as True or False. Inc. On line 11 we begin class LogicalOp- erators. which will inherit from class System. Line 16 starts the constructor for this method. 244 Control Structures: Part 2 Chapter 5 expression1 expression2 expression1 ^ expression2 true false true true true false Fig. 5. Notice that to display a & symbol. The reason this is needed will be discussed in Chapter 26. expression !expression false true true false Fig. 1 // Fig. the strings “False” and “True” indicate false and true for the operands in each condition. and not LogicalOperators. 7/18/01 . Figure 5.18.Form. the programmer can avoid using logical negation by expressing the con- dition differently with an appropriate relational or equality operator. The program uses string concatenation to create the string that is displayed by a label on a form. ^ and! operators.Forms.WriteLine( "The next grade is " + grade ). 5. Lines 22–26 demonstrate the && operator.cs 2 // Demonstrating the logical operators. The parentheses around the condition grade == sentinelValue are needed because the logical negation operator has a higher precedence than the equality operator. All Rights Reserved. The application of Fig. Lines 20–56 contain most of the code for this program.18: LogicalOperators.16 Truth table for the boolean logical exclusive OR (^) operator (part 2 of 2). We have manually changed this everywhere in the program. 5. 5. while the rest is used to display the output on a form.Windows. In most cases. the pre- ceding statement may also be written as follows: if ( grade != sentinelValue ) Console. Fig. while lines 34–38 demonstrate the & operator. In the output of Fig. C# automatically adds the string “False” or “True” based on the boolean value.17 is a truth table for the logical negation operator. The rest of the constructor demonstrates the ||. which begins by calling InitializeComponent (line 18). 5.

Drawing.Windows. 19 20 string output = "". Inc. 7/18/01 .Form 12 { 13 private System.Container components = null. 9 using System. 14 private System.Windows. Fig. All Rights Reserved.ComponentModel. 5 using System. 55 56 outputLabel. 33 34 output += "\n\nBoolean logical AND (&&)" + 35 "\nfalse && false: " + ( false & false ) + 36 "\nfalse && true: " + ( false & true ) + 37 "\ntrue && false: " + ( true & false ) + 38 "\ntrue && true: " + ( true & true ). 8 using System. 45 46 output += "\n\nBoolean logical exclusive OR (^)" + 47 "\nfalse ^ false: " + ( false ^ false ) + 48 "\nfalse ^ true: " + ( false ^ true ) + 49 "\ntrue ^ false: " + ( true ^ false ) + 50 "\ntrue ^ true: " + ( true ^ true ).Collections. 51 52 output += "\n\nLogical NOT (!)" + 53 "\n!false: " + ( !false ) + 54 "\ntrue: " + ( !true ). Chapter 5 Control Structures: Part 2 245 3 4 using System.18 Demonstrating the logical operators (part 2 of 4) © Copyright 1992–2002 by Deitel & Associates.ComponentModel. 21 22 output = "Logical AND (&&&&)" + 23 "\nfalse &&&& false: " + ( false && false ) + 24 "\nfalse &&&& true: " + ( false && true ) + 25 "\ntrue &&&& false: " + ( true && false ) + 26 "\ntrue &&&& true: " + ( true && true ).Text = output. 7 using System. 27 28 output += "\n\nLogical OR (||)" + 29 "\nfalse || false: " + ( false || false ) + 30 "\nfalse || true: " + ( false || true ) + 31 "\ntrue || false: " + ( true || false ) + 32 "\ntrue || true: " + ( true || true ).Forms.Windows.Data.Forms. 15 16 public LogicalOperators() 17 { 18 InitializeComponent(). 10 11 public class LogicalOperators : System. 39 40 output += "\n\nBoolean logical inclusive OR (|)" + 41 "\nfalse | false: " + ( false | false ) + 42 "\nfalse | true: " + ( false | true ) + 43 "\ntrue | false: " + ( true | false ) + 44 "\ntrue | true: " + ( true | true ). 6 using System.Forms.Label outputLabel. 5.

424). 8).outputLabel.Drawing. 76 // 77 // outputLabel 78 // 79 this. 437).AutoScaleBaseSize = new System. 246 Control Structures: Part 2 Chapter 5 57 58 } 59 60 protected override void Dispose( bool disposing ) 61 { 62 if ( disposing ) 63 { 64 if ( components != null ) 65 { 66 components.outputLabel.Forms. 93 94 } // end of InitializeComponent 95 96 [STAThread] 97 static void Main() 98 { 99 Application. 81 this. Inc. 88 this.Control[] { 89 {this. 92 this.outputLabel. 90 this.ClientSize = new System.Location = new System. 83 // 84 // LogicalOperators 85 // 86 this.Name = "outputLabel".Size(5. 67 } 68 } 69 base.Windows.outputLabel = new System.Text = "LogicalOperators".Point(8. 80 this.Drawing.AddRange(new System. 91 this.outputLabel}).Windows.Size(280. 100 } 101 102 } // end of class LogicalOperators Fig. 82 this.TabIndex = 0.ResumeLayout(false).18 Demonstrating the logical operators (part 3 of 4) © Copyright 1992–2002 by Deitel & Associates.Name = "LogicalOperators".Drawing.Label().Drawing. 7/18/01 .Dispose( disposing ). 5.Run( new LogicalOperators() ). 70 } 71 72 private void InitializeComponent() 73 { 74 this. All Rights Reserved.outputLabel.Controls. 87 this.Forms.SuspendLayout().Dispose().Size(288. 75 this. 13).Size = new System.

5. Connecting indi- vidual flowchart symbols arbitrarily can lead to unstructured programs. Inc. the pro- gramming profession has chosen to combine flowchart symbols to form a limited set of control structures. debug.19 shows the precedence and associativity of the C# operators intro- duced to this point. Therefore.20 summarizes C#’s control structures. © Copyright 1992–2002 by Deitel & Associates. Our field is younger than architecture is. Small circles are used in the figure to indicate the single entry point and the single exit point of each structure. All Rights Reserved. and our collective wisdom is considerably sparser. so should programmers design programs. Figure 5. 7/18/01 . modify and even prove correct in a mathematical sense. 5. The operators are shown from top to bottom in decreasing order of pre- cedence. We have learned that structured programming produces programs that are easier than unstructured programs to understand and hence are easier to test. and to build structured programs by properly combining control struc- tures in two simple ways. 5.9 Structured Programming Summary Just as architects design buildings by employing the collective wisdom of their profession. Chapter 5 Control Structures: Part 2 247 Fig.18 Demonstrating the logical operators (part 4 of 4) The chart in Fig.

Figure 5. For example. replacing each of these rectangles with double-selection structures. the rectangle in the simplest flowchart is first replaced with a double-selection (if/else) structure. in Fig. 7/18/01 .24. only single-entry/single-exit control structures are used—there is only one way to enter and only one way to exit each control structure.e.19 Precedence and associativity of the operators discussed so far. Rule 3 is called the nesting rule. Repeatedly applying rule 3 to the simplest flowchart results in a flowchart with neatly nested control structures. Then rule 3 is applied again to both of the rectangles in the double-selection struc- ture. repeatedly applying rule 2 to the sim- plest flowchart results in a structured flowchart containing many rectangles in sequence (Fig.21 always results in a structured flowchart with a neat. For example.. © Copyright 1992–2002 by Deitel & Associates. For simplicity.+ . The rules assume that the rectangle flowchart symbol may be used to indicate any action.22). building-block appearance (Fig.21 shows the rules for forming properly structured programs. including input/output. Applying the rules of Fig. The dashed boxes around each of the double-selection structures represent the rectangle that was replaced in the original simplest flowchart.! (type) right to left unary * / % left to right multiplicative + .248 Control Structures: Part 2 Chapter 5 Operators Associativity Type () ++ -. All Rights Reserved. 5. left to right additive < <= > >= left to right relational == != left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR | left to right boolean logical inclusive OR && left to right logical AND || left to right logical OR ?: right to left conditional = += -= *= /= %= right to left assignment Fig.23). Inc. we have called this “control structure stacking. mixed parentheses and unary postfix ++ -. so let us call rule 2 the stacking rule. Connecting control struc- tures in sequence to form structured programs is simple—the exit point of one control struc- ture is connected to the entry point of the next control structure (i.” The rules for forming structured programs also allow for control structures to be nested. 5. 5. 5. 5. Notice that rule 2 generates a stack of control structures. the control structures are simply placed one after another in a program).

All Rights Reserved. 7/18/01 .20 C#’s single-entry/single-exit sequence.Chapter 5 Control Structures: Part 2 249 do/while structure T while structure R e p e t i ti o n F for structure T T F F (double selection) if/else structure T break break break Se l ec t i o n F (multiple selection) switch structure (single selection) if structure T T T F F F . more involved and more deeply nested structures. Fig. . . 5. Inc. selection and repetition structures. . Rule 4 generates larger. © Copyright 1992–2002 by Deitel & Associates. T F S e q u e n ce .21 constitute the set of all possible structured flowcharts and hence the set of all possible structured programs. 5. . The flow- charts that emerge from applying the rules in Fig.

26) cannot be created.22 Simplest flowchart. Inc. 5. while. 5. 5.21 are followed. Fig.21 Rules for forming structured programs . All Rights Reserved. © Copyright 1992–2002 by Deitel & Associates. 5. Fig. and we assemble them in only two simple ways. If the rules in Fig. an unstructured flowchart (such as that in Fig.25 shows the kinds of stacked building blocks that emerge from applying rule 2 and the kinds of nested building blocks that emerge from applying rule 3. 2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.23 Repeatedly applying rule 2 of Fig. do/while. Rule 2 Rule 2 Rule 2 .21 to the simplest flowchart. 5. 4) Rules 2 and 3 may be applied as often as you like and in any order. Fig. If you are uncertain if a particular flowchart is structured. if. 7/18/01 . The figure also shows the kind of over- lapped building blocks that cannot appear in structured flowcharts (because of the elimina- tion of the goto statement). 3) Any rectangle (action) can be replaced by any control structure (sequence. .250 Control Structures: Part 2 Chapter 5 Rules for Forming Structured Programs 1) Begin with the “simplest flowchart” (Figure 5. .22). for or foreach). The beauty of the structured approach is that we use only eight simple single-entry/ single-exit pieces. 5. if/else. switch. Figure 5.

otherwise. Inc. Structured programming promotes simplicity. 5. 5.Chapter 5 Control Structures: Part 2 251 apply the rules of Fig.21 in reverse to try to reduce the flowchart to the simplest flow- chart. Bohm and Jacopini have given us the result that only three forms of control are needed: • Sequence • Selection • Repetition © Copyright 1992–2002 by Deitel & Associates. the original flowchart is struc- tured. 7/18/01 .21 to the simplest flowchart. Rule 3 Rule 3 Rule 3 Fig.24 Applying rule 3 of Figure 5. If the flowchart is reducible to the simplest flowchart. it is not. All Rights Reserved.

nested and overlapped building blocks. 7/18/01 . 5. it is straightforward to prove that the simple if structure is sufficient to provide any form of selection—everything that can be done with the if/else structure and the switch structure can be implemented by combining if structures (although perhaps not as smoothly). Inc. 5.252 Control Structures: Part 2 Chapter 5 Stacked building blocks Nested building blocks Overlapping building blocks (Illegal in structured programs) Fig.25 Stacked. Repetition is implemented in one of four ways: • while structure • do/while structure • for structure • foreach structure © Copyright 1992–2002 by Deitel & Associates.26 An unstructured flowchart. Selection is implemented in one of three ways: • if structure (single selection) • if/else structure (double selection) • switch structure (multiple selection) In fact. Sequence is trivial. Fig. All Rights Reserved.

All Rights Reserved. We will also discuss how methods promote software reusability. in turn. Inc. • Using an incorrect relational operator or using an incorrect final value of a loop counter in the con- dition of a while. The name of a control variable (or loop counter). expression2 and expression3 placed as follows: expression1. braces ({ and }) are required to define the body of the loop. controlling counting loops with floating-point variables may result in imprecise counter values and inaccurate tests for termination. we introduce another program structuring unit called the method. expression2 is the loop-continuation condition (containing the control variable’s final value) and expression3 in- crements the control variable.Chapter 5 Control Structures: Part 2 253 It is straightforward to prove that the while structure is sufficient to provide any form of repetition.e. We will learn to compose large programs by combining methods that. SUMMARY • Counter-controlled repetition requires: 1. Combining these results illustrates that any form of control ever needed in a C# pro- gram can be expressed in terms of: • sequence • if structure (selection) • while structure (repetition) And these control structures can be combined in only two ways—stacking and nesting. In- deed. • Declarations that include initialization are executable statements. while ( expression2 ) { statement © Copyright 1992–2002 by Deitel & Associates. Everything that can be done with the do/while structure and the for or foreach structure can be done with the while structure (although perhaps not as ele- gantly). In Chapter 6. • The general format of the for structure is for ( expression1. We will then create objects from classes and proceed with our treat- ment of object-oriented programming. structured programming promotes simplicity. are composed of control structures. we discussed how to compose programs from control structures con- taining actions and decisions. 4)The condition that tests for the final value of the control variable (i. expression3 ) statement where expression1 names the loop’s control variable and provides its initial value. • In most cases the for structure can be represented with an equivalent while structure with expression1. • Because floating-point values may be approximate.. we discuss in more detail C#’s other program structuring unit called the class. • If there is more than one statement in the body of the for. expression2. for or do/while structure can cause an off-by-one error. In this chapter. 7/18/01 . 3) The increment (or decrement) by which the control variable is modified each time through the loop (also known as each iteration of the loop). 2) The initial value of the control variable. whether looping should continue). In Chapter 8.

The switch structure consists of a series of case la- bels and an optional default case. Execution continues with the first statement after the structure. } • If the initialization section in the for structure header defines the control variable.. remember that the expression after each case can only be a constant integral expression. • Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch structure. causes immediate exit from that structure. this practice can lead to subtle errors. the statements for all the remaining cases will be executed. when used properly. In the exercises. • The continue statement.e. • When using the switch structure. Inc. a variable that contains a value that does not change for the entire program. • The scope of a variable defines where it can be used in a program.] • C# provides the switch multiple-selection structure to handle a series of decisions in which a variable or expression is tested separately. skips the re- maining statements in the body of that structure and proceeds with the next iteration of the loop. • The break and continue statements alter the flow of control. • The expression after each case can also be a constant variable—i. • The three expressions in the for structure are optional. for or do/while structure. • The two semicolons in the for structure are required.e. The imprecision of floating-point numbers can cause errors that will result in incorrect monetary val- ues. then each time a match occurs in the struc- ture. • The break and continue statements.. perform faster than the cor- responding structured techniques. when executed in a while. any combination of character constants and integer constants that evaluates to a constant integer value). • If break is not used anywhere in a switch structure. therefore. when executed in a while. • C# provides logical operators that may be used to form more complex conditions by combining simple conditions. • Although the value of the control variable can be changed in the body of a for loop. All Rights Reserved. • An optional third argument to method MessageBox. • If the loop-continuation condition is initially false.Show can be used to display an icon on the dialog. (i. the control variable can only be used in the body of the for structure.254 Control Structures: Part 2 Chapter 5 expression3. we explore the use of integers to perform monetary calculations. the body of the for structure is not per- formed. This restricted use of the control vari- able name is known as the variable’s scope. [Note: Class Decimal is available for properly performing monetary calculations. do/while or switch structure. • The do/while structure tests the loop-continuation condition after the loop body is performed. for. • Note that listing case labels together (such as case 'C': case 'c': with no statements be- tween the cases) performs the same set of actions to occur for each of the cases. • The break statement. • Do not use variables of type float or double to perform precise monetary calculations. 7/18/01 . the loop body is always executed at least once. © Copyright 1992–2002 by Deitel & Associates.

• We can use the logical && operator to ensure at some point in a program that two conditions are both true before we choose a certain path of execution. • Structured programming promotes simplicity. • We can use the logical || operator to ensure at some point in a program that one of two (or both) conditions are both true before we choose a certain path of execution. do/while. • The while structure is sufficient to provide any form of repetition. also called logical negation). TERMINOLOGY ! (logical NOT) != ”is not equal to” & (boolean logical AND) && (logical AND) ^ (boolean logical exclusive OR) | (boolean logical inclusive OR) || (logical OR) binary operators © Copyright 1992–2002 by Deitel & Associates. • Repetition is implemented with one of four structures—while. • Bohm and Jacopini have given us the result that only three forms of control are needed—sequence.Chapter 5 Control Structures: Part 2 255 • The logical operators are && (logical AND). • In flowcharts. • Connecting individual flowchart symbols arbitrarily can lead to unstructured programs. • The if structure is sufficient to provide any form of selection. for and foreach. • Connecting control structures in sequence to form structured programs is simple—the exit point of one control structure is connected to the entry point of the next control structure. • When you add a bool value to a string. • The ^ operator evaluates both operands. | (bool- ean logical inclusive OR). and to build structured programs by properly combining control structures in two simple ways. • Control structures can be combined in only two ways—stacking and nesting. • Sequence is trivial. C# automatically adds the string “False” or “True” based on the boolean value.” • The rules for forming structured programs also allow for control structures to be nested. Inc. Therefore. if/else and switch. selection and repetition. All Rights Reserved. 7/18/01 . we have called this “control structure stacking. • Selection is implemented with one of three structures—if. the programming profession has chosen to combine flowchart symbols to form a limited set of control structures. small circles are used in the figure to indicate the single entry point and the single exit point of each structure. • A condition containing the boolean logical exclusive OR (^) operator is true if and only if one of its operands results in a true value and one results in a false value. || (logical OR).\ • C# provides the ! (logical negation) operator to enable a programmer to “reverse” the meaning of a condition. ^ (boolean logical exclusive OR) and! (logical NOT. • The logical negation operator is placed before a condition to choose a path of execution if the orig- inal condition (without the logical negation operator) is false. & (boolean logical AND).

All Rights Reserved.Pow method MessageBoxIcon class MessageBox. 7/18/01 .256 Control Structures: Part 2 Chapter 5 body of a loop bool values break statement building block cases in a switch statement comma-separated list const variable constant integral expression constant variable continue statement control structure control variable controlling expression control-structure stacking De Morgan’s Laws Decimal class decision default case in a switch structure delay loop do/while repetition structure double-selection structure empty statement (semicolon by itself) exponentiation operator factorial final value of control variable flow of control flowchart reducible to the simplest flowchart flowchart symbol for header for repetition structure for structure Form class increment a control variable infinite loop infinite series initial value of a control variable integral expression iteration of a loop levels of nesting logic error logical negation (!) logical operators loop body loop counter loop-continuation condition Math class Math. Inc.Show method multiple-selection structure © Copyright 1992–2002 by Deitel & Associates.

when executed in one of the repetition structures.Chapter 5 Control Structures: Part 2 257 nested control structure nesting nesting rule ”off-by-one error” optimizing compiler polymorphism Pow method scope sentinel-controlled loop short-circuit evaluation stacked building block stacking rule static method structured programming switch multiple-selection structure title bar string truth table unary operator unstructured flowchart variable scope zero-based counting SELF-REVIEW EXERCISES 5. 7/18/01 . causes imme- diate exit from the structure. 5.2 Fill in the blanks in each of the following: a) Specifying the order in which statements are to be executed in a computer program is called __________. h) Infinite loops are caused when the loop-continuation condition is always true. m) The || operator has a higher precedence than the && operator.1 State whether each of the following is true or false. j) The break statement. All Rights Reserved. b) The break statement is required in the default case of a switch selection structure. i) The following syntax will continue the loop while 10 < x < 100: while ( x > 10 && x < 100 ). © Copyright 1992–2002 by Deitel & Associates. c) The expression ( x > y && a < b ) is true if either x > y is true or a < b is true. c) A for loop should use __________ values as its counter. k) The break and continue statements are sometimes thought to violate structured pro- gramming. Inc. g) A for loop requires two commas. d) Forgetting the __________ statement causes the switch structure to execute the next case regardless of whether or not it is true. f) It is a bad idea to use floating point variables in control structures. If false. d) An expression containing the || operator is true if either or both of its operands is true. a) The default case is required in the switch selection structure. e) The expression ( x <= y && y > 4 ) is true if x is less than or equal to y or y is greater than 4. b) Placing a semicolon after a for statement results in a __________ error. l) There is usually no trade-off between good software engineering and high performance. explain why.

d) True. j) True. then there is no need for a default case. Both of the relational expressions must be true in order for the entire expression to be true when using the && operator. The break statement is used to exit the switch structure. 5.pow( 2. The is usually a trade-off between good software engineering and high performance. count += 2 ) sum += count. b) Math. 3 ) c) x = 1. h) In a for loop. for ( count = 1. information.Write( x ). 7/18/01 . The && operator has higher precedence than the || operator. k) Three types of MessageBox icons are exclamation. Inc.WriteLine() method to output the newline character and use the Con- sole. if ( x % 5 == 0 ) Console. print a newline character. ANSWERS TO SELF-REVIEW EXERCISES 5. 5.5. A for loop requires two semicolons in its header and a semi- colon after its body. e) False.258 Control Structures: Part 2 Chapter 5 e) Using the following relational operator in a while-repetition condition that should loop 10 times is known as the __________ error: int x = 1. f) True. c) False.WriteLine(). i) True.] d) Repeat Exercise 5. b) Calculate the value of 2. l) The value in parentheses immediately following the keyword switch is called the __________. and __________. h) True.2 a) program control b) logic c) integer d) break e) off-by-one f) for structure header g) scope h) after i) comma j) loops k) question l) controlling expression 5.3 a) sum = 0. Assume this is an application—use the Con- sole. i) Multiple initializations and incriminations in the for structure header should be separat- ed by a __________. Print only five integers per line. m) False. Assume that the variable x has been declared but not initialized. All Rights Reserved. incrementing occurs __________ the body of the statement. Assume the integer vari- ables sum and count have been declared.3 c) using a for structure. © Copyright 1992–2002 by Deitel & Associates. otherwise. The default case is optional. If no default action is needed. print a tab character. c) Print the integers from 1 to 20 using a while loop and the counter variable x. k) True. l) False. g) False. j) It is poor practice to place expressions whose values do not change inside __________.3 Write a C# statement or a set of C# statements to accomplish each of the following: a) Sum the odd integers between 1 and 99 using a for structure. The expression ( x <= y && y > 4 ) is true if x is less than or equal to y and y is greater than 4. The break statement is not required for the last case in a switch structure. while ( x <= 20 ) { Console.Write( ’\t’ ) method to output the tab character. count <= 99.5 raised to the power of 3 using the pow method. g) A control variable initialized within a for loop has restricted use or __________. while ( x < 10 ) … f) The for structures first line is sometimes known as the __________. When the value of this is 0.1 a) False. [Hint: Use the calculation x % 5. b) False.

first. All asterisks (*) should be printed by a single statement of the form Console.Write( '\t' ). All Rights Reserved. Display the results in tabular format in a MessageBox that is displayed on a message dialog. 5. } d) for ( x = 1. EXERCISES 5.WriteLine( '*' ). if ( x % 5 == 0 ) Console. x++ ) { Console. Place the results in a MessageBox with scrolling functionality. and hexadecimal equivalents of the decimal numbers in the range 1 through 256.WriteLine(). Use a triple-nested for loop that tries all possibilities. x++ ) if ( x % 5 == 0 ) Console. A statement of the form Console. octal. (this causes the asterisks to print side by side).6 (Pythagorean Triples) A right triangle can have sides that are all integers. A statement of the form Console.WriteLine( x ). ++x.WriteLine().7 Write an application that displays the following patterns separately one below the other. Use for loops to generate the patterns. 5. What difficulty might pre- vent you from calculating the factorial of 20? 5. There should be no other output statements in the program. else Console. can be used to position to the next line.WriteLine( ' ' ). can be used display a space for the last two patterns. side2 and the hypot- enuse all no larger than 500. 7/18/01 . (Hint: The last two patterns require that each line begin with an appropriate number of blanks.4 The factorial method is used frequently in probability problems. Inc. This is an ex- ample of “brute force” computing. x <= 20.5 Write an application that prints a table of the binary. If you are not familiar with these number systems.Chapter 5 Control Structures: Part 2 259 else Console.Write( x + "\t" ).Write( x ). Write an application that evaluates the factorials of the integers from 1 to 5. x <= 20.) © Copyright 1992–2002 by Deitel & Associates. The set of three integer values for the sides of a right triangle is called a Pythagorean triple. read Appendix E. You will learn in more advanced computer science courses that there are large numbers of interesting problems for which there is no known algorithmic approach other than using sheer brute force. The factorial of a positive integer n (written n! and pronounced “n factorial”) is equal to the product of the positive integers from 1 to n. else Console. Write an application to find all Pythagorean triples for side1. } or for ( x = 1. These three sides must satisfy the relationship that the sum of the squares of two of the sides is equal to the square of the hypotenuse.Write( '\t' ).

Inc.260 Control Structures: Part 2 Chapter 5 (A) (B) (C) (D) * ********** ********** * ** ********* ********* ** *** ******** ******** *** **** ******* ******* **** ***** ****** ****** ***** ****** ***** ***** ****** ******* **** **** ******* ******** *** *** ******** ********* * ** ********* ********** * * ********** 5. * *** ***** ******* ********* ******* ***** *** * 5. All Rights Reserved.10 Modify the program you wrote in Exercise 5. 7/18/01 . 5.9 Write an application that prints the following diamond shape. Your program should then display a diamond of the ap- propriate size. Maximize your use of rep- etition (with nested for structures) and minimize the number of output statements. © Copyright 1992–2002 by Deitel & Associates. a single space or a single newline character.7 to combine your code from the four separate triangles of asterisks into a single application that prints all four patterns side by side making clever use of nested for loops. You may use output statements that print a single asterisk (*).9 to read an odd number in the range 1 to 19 to specify the number of rows in the diamond.8 Modify Exercise 5.

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

252 braces not required in case E if/else double-selection statements 234 empty statement (semicolon by structure 232. 253 flowcharting a for repetition && (logical AND) 241. 242. 224. 243 control variable name 220. 243 controlling expression 234 for repetition structure 222. 249. 224. A 234 action 253 foreach structure 252 AND operator (boolean logical) D Form class 244 241. 243 control variable 223 structure 226 <= less than or equal 241 control variable final value 220 flowcharting the do/while ^ (boolean logical exclusive OR) control variable inital value 220 repetition structure 238 241. 223. C. 242. 239. Decimal class 231 243 decision 253 arrow 235 default case in a switch G structure 234. 253 222. 221. braces ({ and }) 223. 235 hexadecimal (base16) number body of a loop 221. 263 flowchart symbol 247 243 control structure 220. 249 ‚ (comma) 228 counter variable 234 for structure 223. 252 I IconExclamation 229 boolean logical exclusive OR double selection 252 operator (^) 241. 230. counter-controlled repetition 220. 7/18/01 . 236 infinite series 263 case statement 234 F initial value 221 cases in a switch statement factorial 259 initial value of a control variable 234 fill rectangles 262 220 comma (‚) 228 fillRect of class Graphics 262 Initial value of control variable comma in a for header 228 final value 221 223. 242. 252. 243 control-structure stacking 248 226. 226 do/while flowchart 238 system 259 Bohm. || (logical OR) 241. 243 if single-selection structure 232. 237 case label 234. 238. 226. 243 De Morgan’s Laws 263 forming structured programs 248 AND operator (logical) 241. 226 initialization section of the for compound interest 229. 243 236. flowchart 251 & (boolean logical AND) 241. 226 comma-separated list 224 final value of control variable initialization 225 compiler 227 220. 243 IconInformation 229 double-selection structure 248 boolean logical inclusive OR IconQuestion 229 drawRect method 262 operator (|) 241. All Rights Reserved. 228 241. 223 for structure header 223. 238. itself) 237 increment 224 263 entry point of a control structure increment a control variable 221. 248 248 226 exit point of a control structure increment expression 239 248 increment of a for structure 226 C exponentiation operator 230 increment of control variable 223 C# compiler 227 infinite loop 225. building block 220. 235. 262 flow of control 226 structure 228 © Copyright 1992–2002 by Deitel & Associates. 252 break statement 234. for flowchart 226 | (boolean logical inclusive OR) 224 for header 225.Index 1 Symbols const variable 236 flowchart of for statement 226 ! (logical NOT) 241. 235 goto statement 250 delay loop 225 graph 262 B dependent condition 242 bar chart 262 dialog box 228 binary 259 diamond 260 H binary operators 243 diamond symbol 226. 244 constant integral expression 236 flowchart reducible to the simplest != ”is not equal to” 241 continue statement 238. 243. 237 249. 251 do/while repetition structure histogram 262 bool values 244 249 boolean logical AND operator (&) do/while repitition structure 241. Inc.

inclusive) 241. 251 nesting rule 248 selection. 249. integral expression 236 221 simple condition 241 interest rate 229 nested building block 250. 252 mation 229 MessageBox. 227. 231. Jacopini. 243 overlapped building block 250. 251. 236 252 class 244 loop counter 220 loop-continuation condition 221.Form loop body 225. optimizing compiler 231 static method 230 242. Inc. 262 while structure 252 monetary calculations 231 selection 248. 252 simplest flowchart 250. 235. 261 U message dialog types 228 R rectangle symbol 226. 253 Z 252 short-circuit evaluation 242 zero-based counting 224.Pow method 230. logical negation (!) 241.2 Index InitializeComponent N Show method 231 method 244 side effect 243 name of a control variable 220.WinForms. output 223 249. sequence 248. 243 240. 225. switch multiple-selection logical operators 241.Show method savings account 229 231 scope 224 W method 253 scope of a variable 224 while repetition structure 249 modulus operation 262 scrolling 259. round 231 ”rule of thumb” 240 mation 229 V MessageBox. 234. 243 switch logic 236 243. 252 unstructured flowchart 250. and repetition JOptionPane constants for NOT operator (logical) 241. G.IconExcla- repetition 249. 235. P T 223. exclusive) 241. 225. 234 © Copyright 1992–2002 by Deitel & Associates. All Rights Reserved. 231 Pythagorean Triples 259 AND) operator 242 message dialog 228. 234. 7/18/01 . 251 iteration of a loop 220. 264 loop-continuation test 239 Pow method 230. 251. 243. 243 OR operator (boolean logical structured programming 220. 248 unary operator 243 MessageBox. 243 243 structure 232. polymorphism 236 ”The Twelve Days of Christmas” 236. 252 MSDN documentation 228 sentinel-controlled loop 262 multiple-selection structure 235. 234. 243. structures 249 message dialog 249 244 small circle symbol 235 smallest of several integers 261 L O stacked building block 250 levels of nesting 222 octal (base8) 259 stacking 253 logic error 223 ”off-by-one error” 223. 224 stacking rule 248 logical AND operator (&&) 241. 252 242.IconInfor. System. 249. 251. logical OR operator (||) 241.IconQues- variable scope 224 tion 229 S MessageBox. 231 title bar string 228 preincrementing 225 truth table 241 principal 229 M product of odd integer 261 truth table for operator ! (logical Main method 223 NOT) 244 program construction principles Math class 230 220 truth table for the && (logical Math. 237 postincrementing 225 song 234. 239 nested control structure 235 single selection 252 nested switch structure 235 single-entry/single-exit control nesting 253 structure 248 J nesting control structures 222 single-entry/single-exit sequence. 242. 224. 253 244 OR operator (boolean logical structured techniques 240 logical NOT operator (!) 241. 244 OR operator (logical) 241.