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

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.

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

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 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.

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).

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.

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.

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.

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.

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.

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.

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.