Sie sind auf Seite 1von 46

1

Chapter 5 – Control Structures: Part 2


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

 2001 Prentice Hall, Inc. All rights reserved.


2
5.2 Essentials of Counter Controlled
Repetition
• Counter controlled repetition
– Control variable
• The variable used to determine if the loop continues
– Initial value of the control variable
– Incrementing/decrementing of the variable
– The condition
• When the looping should continue

 2001 Prentice Hall, Inc. All rights reserved.


3
1 // Fig. 5.1: WhileCounter.cs Outline
2 // Counter-controlled repetition.
3
4 using System;
5 WhileCounter.cs
6 class WhileCounter
7 { This is where the counter variable
8 static void Main( string[] args )
is initialized. It is set to 1.
9 {
10 int counter = 1; // initialization
11 The loop will continue until counter is
12 while ( counter <= 5 ) // repetition
greater condition
than five (it will stop once it
13 {
14 Console.WriteLine( counter ); gets to six)
15 counter++; // increment
16
The counter is incremented
17 } // end while and 1 is added to it
18
19 } // end method Main
20
21 } // end class WhileCounter

1 Program Output
2
3
4
5

 2001 Prentice Hall, Inc.


All rights reserved.
4

5.3 for Repetition Structure

• The for repetition structure


– Syntax: for (Expression1, Expression2, Expression3)
• Expression1 = names the control variable
– Can contain several variables
• Expression2 = loop-continuation condition
• Expression3 = incrementing/decrementing
– If Expression1 has several variables, Expression3 must
have several variables accordingly
– ++counter and counter++ are equivalent
– Variable scope
• Expression1 can only be used in the body of the for loop
• When the loop ends the variable expires

 2001 Prentice Hall, Inc. All rights reserved.


5

5.3 for Repetition Structure

for keyword Control variable name Final value of control variable

for ( int counter = 1; counter <= 5; counter++ )

Initial value of control variable Increment of control variable


Loop-continuation condition

Fig. 5.3 Components of a typical for header.

 2001 Prentice Hall, Inc. All rights reserved.


6

5.3 for Repetition Structure

Establish initial value


int counter = 1
of control variable.

Determine if final
value of control true Console.WriteLine
counter <= 10 counter++
variable has been ( counter * 10 );
reached.
Increment the
false Body of loop (this may be control variable.
multiple statements)

Fig. 5.4 Flowcharting a typical for repetition structure.

 2001 Prentice Hall, Inc. All rights reserved.


7
1 // Fig. 5.2: ForCounter.cs Outline
2 // Counter-controlled repetition with the for structure.
3 This is where the counter variable
4 using is initialized. It is set to 1.
System;
5 The counter is incremented ForCounter.cs
6 class ForCounter
7 { The loop will(1continue
is addeduntil
to it)counter is
8 static void Main( string[] args
greater than five) (it will stop once it
9 {
10
gets to six)
// initialization, repetition condition and incrementing
11 // are all included in the for structure
12 for ( int counter = 1; counter <= 5; counter++ )
13 Console.WriteLine( counter );
14 }
15 }

1 Program Output
2
3
4
5

 2001 Prentice Hall, Inc.


All rights reserved.
8

5.4 Examples Using the for Structure

• Increment/Decrement
– When incrementing
• In most cases < or <= is used
– When decrementing
• In most cases > or >= is used
• Message boxes
– Buttons
• OK
• OKCancel
• YesNo
• AbortRetryIgnore
• YesNoCancel
• RetryCancel

 2001 Prentice Hall, Inc. All rights reserved.


9

5.4 Examples Using the for Structure

• Massages boxes
– Icons
• Exclamation
• Question
• Error
• Information

• Formatting
– (variable : format)
• Table 5.9 lists some formatting codes

 2001 Prentice Hall, Inc. All rights reserved.


10
1 // Fig. 5.5: Sum.cs Outline
2 // Summation with the for structure.
3
4 using System;
5 using System.Windows.Forms; Sum.cs
6
7 class Sum Once the number is greater
8 { The counter. It is initialized to 2 than 100 the loop breaks
9 static void Main( string[] args ) Increments number by 2
10 {
11 int sum = 0; every time the loop starts over
12
13
The caption of the message box
for ( int number = 2; number <= 100; number += 2 )
The title of the message box
14 sum += number;
15
16 MessageBox.Show( "The sum is " + sum,
17 "Sum Even Integers from 2 to 100", Displays a message box with an OK button
18 MessageBoxButtons.OK,
19 MessageBoxIcon.Information ); Has the message box contain
20 an information icon
21 } // end method Main
22
23 } // end class Sum

Argument 4:
MessageBox Icon Program Output
(Optional) Argument 2: Title bar
string (Optional)

Argument 3: OK dialog Argument 1: Message


button. (Optional) to display

 2001 Prentice Hall, Inc.


All rights reserved.
11

5.4 Examples Using the for Structure

Messa g eBox Ic ons Ic on Desc rip tion


MessageBoxIcon.Exclamation Displays a dialog with an
exclamation point. Typically
used to caution the user against
potential problems.
MessageBoxIcon.Information Displays a dialog with an
informational message to the
user.

MessageBoxIcon.Question Displays a dialog with a question


mark. Typically used to ask the
user a question.
MessageBoxIcon.Error Displays a dialog with an x in a
red circle. Helps alert user of
errors or important messages.
Fig. 5.6 Ic ons for m essa g e d ia log s.

 2001 Prentice Hall, Inc. All rights reserved.


12

5.4 Examples Using the for Structure


Me ssa g eBox Butto ns De sc rip tio n
MessageBoxButton.OK Specifies that the dialog should include an OK button.

MessageBoxButton.OKCancel Specifies that the dialog should include OK and Cancel


buttons. Warns the user about some condition and allows
the user to either continue or cancel an operation.

MessageBoxButton.YesNo Specifies that the dialog should contain Yes and No


buttons. Used to ask the user a question.

MessageBoxButton.YesNoCancel Specifies that the dialog should contain Yes, No and


Cancel buttons. Typically used to ask the user a question
but still allows the user to cancel the operation.

MessageBoxButton.RetryCancel Specifies that the dialog should contain Retry and Cancel
buttons. Typically used to inform a user about a failed
operation and allow the user to retry or cancel the operation.

MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort, Retry and
Ignore buttons. Typically used to inform the user that one
of a series of operations has failed and allow the user to
abort the series of operations, retry the failed operation or
ignore the failed operation and continue.

Fig. 5.7 Buttons fo r m essa g e d ia lo g s.

 2001 Prentice Hall, Inc. All rights reserved.


13
1 // Fig. 5.8: Interest.cs Outline
2 // Calculating compound interest.
3
4 using System;
5 using System.Windows.Forms; Interest.cs
6
7 class Interest
8 {
9 static void Main( string[] args )
10 { Loops through 10 times
11 decimal amount, principal =starting
( decimal ) 1000.00;
at 1 and ending at 10,
12 double rate = .05;
13 string output; adding 1 to the counter (year)
14 each time
15 output = "Year\tAmount on deposit\n";
16 Formats amount to have a
17 for ( int year = 1; year <= 10; year++ )
18 { currency formatting ($0.00)
19 amount = principal *
20 ( decimal ) Math.Pow( 1.0 + rate, year );
21 Insert a Tab Creates a message box that displays the
22 output += year + "\t" + output with a title of “Compound Interest”
23 String.Format( "{0:C}", amount ) + "\n";
24 } has an OK button and an information icon
25
26 MessageBox.Show( output, "Compound Interest",
27 MessageBoxButtons.OK, MessageBoxIcon.Information );
28
29 } // end method Main
30
31 } // end class Interest

 2001 Prentice Hall, Inc.


All rights reserved.
14
Outline

Interest.cs
Program Output

 2001 Prentice Hall, Inc.


All rights reserved.
15

5.4 Examples Using the for Structure

Forma t C od e De sc rip tio n


C or c Formats the string as currency. Precedes the number with an appropriate currency
symbol ($ in the US). Separates digits with an appropriate separator character
(comma in the US) and sets the number of decimal places to two by default.

D or d Formats the string as a decimal. Displays number as an integer.


N or n Formats the string with commas and two decimal places.
E or e Formats the number using scientific notation with a default of six decimal places.

F or f Formats the string with a fixed number of decimal places (two by default).
G or g General. Either E or F.
X or x Formats the string as hexadecimal.
Fig. 5.9 string form a tting c od es.

 2001 Prentice Hall, Inc. All rights reserved.


16

5.5 switch Multiple-Selection Structure

• The switch statement


– Constant expressions
• String
• Integral
– Cases
• Case ‘x’ :
– Use of constant variable cases
• Empty cases
• The default case
– The break statement
• Exit the switch statement

 2001 Prentice Hall, Inc. All rights reserved.


17
1 // Fig. 5.10: SwitchTest.cs Outline
2 // Counting letter grades.
3
4 using System;
5 SwitchTest.cs
6 class SwitchTest
7 {
8 static void Main( string[] args )
9 {
10 char grade; // one grade
11 A for int aCount = 0, //i to
loop that initializes 1, loops
number of 10
As
12 bCount = 0, // number
times and increments i by one each time of Bs Each of these variables acts as a
13 cCount = 0, // number of Cs counter so they are initialized to zero
14 dCount = 0, // number of Ds
15 fCount = 0; // number of Fs Prompt the user for a grade and
16 store it into the grade variable
17 for ( int i = 1; i <= 10; i++ )
18 {
19 Console.Write( "Enter a letter grade: The start of the switch
" );
20 grade = Char.Parse( Console.ReadLine() );
statement. The grade variable is
21 Both cases add one to aCount
used as the data to be tested for
22 switch ( grade )
23 { each
casecase.
‘A’ is empty so it is the
24 case 'A': // grade is uppercase same
A as case ‘a’
25 case 'a': // or lowercase a
26 ++aCount; The break statement is used to exit the
27 break;
28 switch statement and not perform the rest
29 case 'B': // grade is uppercase of B the operations
30 case 'b': // or lowercase b
31 ++bCount;
Both case ‘B’ and case ‘b’ add one
32 break;
33 to the bCount variable
 2001 Prentice Hall, Inc.
All rights reserved.
18
34 case 'C': // grade
Bothis uppercase
cases add 1 toCcCount Outline
35 case 'c': // or lowercase c
36 ++cCount;
37 break;
38 SwitchTest.cs
39 case 'D': // grade is uppercase D
40 case 'd': // or lowercase d
If grade equals D or d
41 ++dCount;
42 break;
add one to dCount
43
44 case 'F': // grade is uppercase F
45 case 'f': // or lowercase f one to
Add fCount if grade equals F or f
46 ++fCount;
47 break;
48
49 default: If non of the cases are equal to the value of
// processes all other characters
50 Console.WriteLine( grade then the default case is executed
51 "Incorrect letter grade entered." +
52 "\nGrade not added to totals." );
53 break;
54
55 } // end switch Display the results
56
57 } // end for
58
59 Console.WriteLine(
60 "\nTotals for each letter grade are:\nA: {0}" +
61 "\nB: {1}\nC: {2}\nD: {3}\nF: {4}", aCount, bCount,
62 cCount, dCount, fCount );
63
64 } // end method Main
65
66 } // end class SwitchTest
 2001 Prentice Hall, Inc.
All rights reserved.
19
Enter a letter grade: a Outline
Enter a letter grade: A
Enter a letter grade: c
Enter a letter grade: F
Enter a letter grade: z SwitchTest.cs
Incorrect letter grade entered. Program Output
Grade not added to totals.
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

Totals for each letter grade are:


A: 3
B: 1
C: 2
D: 2
F: 1

 2001 Prentice Hall, Inc.


All rights reserved.
20

5.5 switch Multiple-Selection Structure

true
case: a case a action(s) break;

false

true
case: b case b action(s) break;

false

.
.
.

true
case: z case z action(s) break;

false
default action(s)

break;

Fig. 5.11 Flowcharting the switch multiple-selection structure.

 2001 Prentice Hall, Inc. All rights reserved.


21

5.6 do/while Repetition Structure

• The while loops vs. the do/while loops


– Using a while loop
• Condition is tested
• The the action is performed
• Loop could be skipped altogether
– Using a do/while loop
• Action is performed
• Then the loop condition is tested
• Loop must be run though once
• Always uses brackets ({) to prevent confusion

 2001 Prentice Hall, Inc. All rights reserved.


22
1 // Fig. 5.12: DoWhileLoop.cs Outline
2 // The do/while repetition structure.
3
4 using System;
5 DoWhileLoop.cs
6 class DoWhileLoop
7 {
8 static void Main( string[] args )
9 { The counter is initialized to one
10 int counter = 1;
11
12 do
13 {
14 Console.WriteLine( counter );
15 counter++; These actions are performed at least one
16 } while ( counter <= 5 );
17
18 } // end method Main
19 The incrementing task Continue looping as long as counter is less than 6
20 } // end class DoWhileLoop

1
2 Program Output
3
4
5

 2001 Prentice Hall, Inc.


All rights reserved.
23

5.6 do/while Repetition Structure

action(s)

true
condition

false

Fig. 5.13 Flowcharting the do/while repetition structure.

 2001 Prentice Hall, Inc. All rights reserved.


24

5.7 Statements break and continue

• Use
– Used to alter the flow of control
– The break statement
• Used to exit a loop early
– The continue statement
• Used to skip the rest of the statements and begin the loop at the
first statement in the loop
– Programs can be completed without their usage

 2001 Prentice Hall, Inc. All rights reserved.


25
1 // Fig. 5.14: BreakTest.cs Outline
2 // Using the break statement in a for structure.
3
4 using System;
5 using System.Windows.Forms; BreakTest.cs
6
7 class BreakTest
8 {
9 static void Main(
A loopstring[]
that startsargs ) goes
at one,
10 {
11 to ten,= and
string output ""; increments by one
12 int count;
13
14 for ( count = 1; count <= 10; count++ )
15 {
16 if ( count == 5 )
17 break; If //
count = 5remaining
skip then breakcode
out of
inthe loop
loop
18 // if count == 5 Displays a message box the displays the
19
Display the last value that the
output, has a title of “demonstrating the
20 counter was output
at before
+=it count
broke + " ";
21 break statement,” uses an OK button,
22 } // end for loop and displays an information icon
23
24 output += "\nBroke out of loop at count = " + count;
25
26 MessageBox.Show( output, "Demonstrating the break statement",
27 MessageBoxButtons.OK, MessageBoxIcon.Information );
28
29 } // end method Main
30
31 } // end class BreakTest

 2001 Prentice Hall, Inc.


All rights reserved.
26
Outline

BreakTest.cs
Program Output

 2001 Prentice Hall, Inc.


All rights reserved.
27
1 // Fig. 5.15: ContinueTest.cs Outline
2 // Using the continue statement in a for structure.
3
4 using System;
5 using System.Windows.Forms; ContinueTest.cs
6
7 class ContinueTest A loop that starts at 1, goes
8 {
to 10, and increments by 1
9 static void Main( string[] args )If count = 5 then continue looping causing
10 { the program to skip the rest of the loop
11 string output = "";
12
13 for ( int count = 1; count <= 10; count++ )
14 {
15 if ( count == 5 )
16 continue; Create a message
// skip box that
remaining codedisplays
in loopthe output, has
17 the//
title “using
only the continue
if count == 5 statement,” uses an
18
19 output += count +OK button,
" "; and displays an information icon.
20 }
21
22 output += "\nUsed continue to skip printing 5";
23
24 MessageBox.Show( output, "Using the continue statement",
25 MessageBoxButtons.OK, MessageBoxIcon.Information );
26
27 } // end method Main
28
29 } // end class ContinueTest

 2001 Prentice Hall, Inc.


All rights reserved.
28
Outline

ContinueTest.cs
Program Output

 2001 Prentice Hall, Inc.


All rights reserved.
29

5.8 Logical and Conditional Operators

• Operators
– Logical AND (&)
– Conditional AND (&&)
– Logical OR (|)
– Conditional OR (||)
– Logical exclusive OR or XOR (^)
– Logical NOT (!)
• Can be avoided if desired by using other conditional operators
• Used to add multiple conditions to a statement

 2001 Prentice Hall, Inc. All rights reserved.


30

5.8 Logical and Conditional Operators


exp ression1 exp ression2 exp ression1 &&
exp ression2
false false false
false true false
true false false
true true true
Fig. 5.16 Truth ta b le for the && (log ic a l AND) op era tor.

exp ression1 exp ression2 exp ression1 ||


exp ression2
false false false
false true true
true false true
true true true
Fig. 5.17 Truth ta b le for the || (log ic a l OR) op era tor.

 2001 Prentice Hall, Inc. All rights reserved.


31

5.8 Logical and Conditional Operators

exp ression1 exp ression2 exp ression1 ^


exp ression2
false false false
false true true
true false true
true true false
Fig. 5.18 Truth ta b le for the log ic a l exc lusive OR ( ^) op era tor.

exp ression !exp ression


false true
True false
Fig. 5.19 Truth ta b le for op era tor! (log ic a l NOT).

 2001 Prentice Hall, Inc. All rights reserved.


32
1 // Fig. 5.20: LogicalOperators.cs Outline
2 // Demonstrating the logical operators.
3 using System;
4
5 class LogicalOperators LogicalOperators.cs
6 { Outputs a truth table for the
7 // main entry point for application conditional AND operator (&&)
8 static void Main( string[] args )
9 {
10 // testing the conditional AND operator (&&)
11 Console.WriteLine( "Conditional AND (&&)" +
12 "\nfalse && false: " + ( false && false ) +Only true if both inputs are true
13 "\nfalse && true: " + ( false && true ) +
14 "\ntrue && false: " + ( true && false ) +
15 "\ntrue && true: " + ( true && true ) );
16
17 // testing the conditional OR operator (||) Outputs a truth table for the
18 Console.WriteLine( "\n\nConditional OR (||)" + conditional OR operator (||)
19 "\nfalse || false: " + ( false || false ) +
20 "\nfalse || true: " + ( false || true ) + Only false if both inputs are false
21 "\ntrue || false: " + ( true || false ) +
22 "\ntrue || true: " + ( true || true ) );
23
24 // testing the logical AND operator (&)
Outputs a truth table for the
25 Console.WriteLine( "\n\nLogical AND (&)" + logical AND operator (&)
26 "\nfalse & false: " + ( false & false ) +
27 "\nfalse & true: " + ( false & true ) +
28 "\ntrue & false: " + ( true & false ) +
29 "\ntrue & true: " + ( true & true ) );
30

The result is only true if both are true


 2001 Prentice Hall, Inc.
All rights reserved.
33
31
32
// testing the logical OR operator (|)
Console.WriteLine( "\n\nLogical OR (|)" +
Outputs a truth table forOutline
the
33 "\nfalse | false: " + ( false | false ) + logical OR operator (|)
34 "\nfalse | true: " + ( false | true ) +
35 "\ntrue | false: " + ( true | false ) + LogicalOperators.cs
36 "\ntrue | true: " + ( true | true ) ); If one is true the result is true
37
38 // testing the logical exclusive OR operator (^)
39 Console.WriteLine( "\n\nLogical exclusive OR (^)" + Outputs a truth table for the
40 "\nfalse ^ false: " + ( false ^ false ) + logical exclusive OR operator
41 "\nfalse ^ true: " + ( false ^ true ) +
42 "\ntrue ^ false: " + ( true ^ false ) +
(^) false when the two
Returns
43 "\ntrue ^ true: " + ( true ^ true ) ); conditionals are the same
44
45 // testing the logical NOT operator (!)
46 Console.WriteLine( "\n\nLogical NOT (!)" +
Outputs a truth table for the
47 "\n!false: " + ( !false ) + logical NOT operator (!)
48 "\n!true: " + ( !true ) );
49 }
50 } Returns the opposite as the input

Conditional AND (&&) Program Output


false && false: False
false && true: False
true && false: False
true && true: True

Conditional OR (||)
false || false: False
false || true: True
true || false: True
true || true: True
 2001 Prentice Hall, Inc.
All rights reserved.
34
Logical AND (&) Outline
false & false: False
false & true: False
true & false: False
true & true: True LogicalOperators.cs
Program Output
Logical OR (|)
false | false: False
false | true: True
true | false: True
true | true: True

Logical exclusive OR (^)


false ^ false: False
false ^ true: True
true ^ false: True
true ^ true: False

Logical NOT (!)


!false: True
!true: False

 2001 Prentice Hall, Inc.


All rights reserved.
35

5.9 Structured Programming Summary

• Control Structures
– Only one entrance
– Only one exit
– Building blocks to programming
– Allow nesting
– Makes code neater and easier to follow
– No overlapping structures
• The goto keyword

 2001 Prentice Hall, Inc. All rights reserved.


36

5.9 Structured Programming Summary

• 3 forms of control necessary


– Many ways to implement these controls
– Sequential (only 1 way)
• Straight forward programming
– Selection (3 ways)
• if selection (one choice)
• if/else selection (two choices)
• switch statement (multiple choices)
– Repetition (4 ways)
• while structure
• do/while structure
• for structure
• foreach structure (chapter 7)

 2001 Prentice Hall, Inc. All rights reserved.


37

5.9 Structured Programming Summary

Op e ra to rs Asso c ia tivity Typ e


() left to right parentheses
++ -- right to left unary postfix
++ -- + - ! (type) right to left unary prefix
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
& left to right logical AND
^ left to right logical exclusive OR
| left to right logical inclusive OR
&& left to right conditional AND
|| left to right conditional OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 5.21 Prec ed enc e a nd a sso c ia tivity o f the o p e ra to rs d isc ussed so fa r.

 2001 Prentice Hall, Inc. All rights reserved.


38

5.9 Structured Programming Summary


Sequence

.
.

Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 1)

 2001 Prentice Hall, Inc. All rights reserved.


39

5.9 Structured Programming Summary


Selection switch structure
(multiple selections)
else/if structure
T
(double selection) break
F T
F
T
break
F
.
..
if structure
(single selection) T break
T F

F
break

Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 2)

 2001 Prentice Hall, Inc. All rights reserved.


40

5.9 Structured Programming Summary


Repetition

while structure for structure/foreach structure

do/while structure F

Fig. 5.22 C#’s single-entry/single-exit sequence, selection and repetition structures. (part 3)

 2001 Prentice Hall, Inc. All rights reserved.


41

5.9 Structured Programming Summary

Rules for Forming Struc tured Prog ra ms


1) Begin with the “simplest flowchart” (Fig. 5.24).
2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.
3) Any rectangle (action) can be replaced by any control structure (sequence, if,
if/else, switch, while, do/while, for or foreach, as we will see in
Chapter 8, Object-Oriented Programming).
4) Rules 2 and 3 may be applied as often as you like and in any order.
Fig. 5.23 Rules for forming struc tured p rog ra ms.

 2001 Prentice Hall, Inc. All rights reserved.


42

5.9 Structured Programming Summary

Fig. 5.24 Simplest flowchart.

 2001 Prentice Hall, Inc. All rights reserved.


43

5.9 Structured Programming Summary

Rule 2 Rule 2 Rule 2

.
.
.

Fig. 5.25 Repeatedly applying rule 2 of Fig. 5.23 to the simplest flowchart.

 2001 Prentice Hall, Inc. All rights reserved.


44

5.9 Structured Programming Summary

Rule 3

Rule 3

Fig. 5.26 Applying rule 3 of Fig. 5.23 to the simplest flowchart.

 2001 Prentice Hall, Inc. All rights reserved.


45

5.9 Structured Programming Summary

Stacked building blocks Nested building blocks

Overlapping building blocks


(illegal in structured programs)

Fig. 5.27 Stacked, nested and overlapped building blocks.

 2001 Prentice Hall, Inc. All rights reserved.


46

5.9 Structured Programming Summary

Fig. 5.28 Unstructured flowchart.

 2001 Prentice Hall, Inc. All rights reserved.

Das könnte Ihnen auch gefallen