Anda di halaman 1dari 45

1

Chapter 4 Control Structures Part 1


Outline
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
4.9
4.10

4.11
4.12
4.13

Introduction
Algorithms
Pseudocode
Control Structures
if Selection Structure
if/else Selection Structure
while Repetition Structure
Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 2 (Sentinel-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise Refinement:
Case Study 3 (Nested Control Structures)
Assignment Operators
Increment and Decrement Operators
Introduction to Windows Application Programming

2002 Prentice Hall. All rights reserved.

4.1 Introduction
Before writing a program

Understand the problem


Think of an approach
Understand building blocks
Use proven principals of structured programming

2002 Prentice Hall. All rights reserved.

4.2 Algorithms
Procedure
The actions a program will perform
The order these actions will be performed
Also called an algorithm

Program control

The task of ordering a computers procedure correctly

2002 Prentice Hall. All rights reserved.

4.3 Pseudocode
Pseudocode

Artificial and informal language


Helps programmers to plan an algorithm
Similar to everyday English
Not an actual programming language
Converting simply replaces words with C# code

2002 Prentice Hall. All rights reserved.

4.4 Control Structures


Program of control
Program performs one statement then goes to next line
Sequential execution

Different statement other than the next one executes

Selection structure
The if and if/else statements
The goto statement
No longer used unless absolutely needed
Causes many readability problems
Repetition structure
The while and do/while loops (chapter 5)
The for and foreach loops (chapter 5)

2002 Prentice Hall. All rights reserved.

4.4 Control Structures


Flow carts
Used to map program
Illustrates the order events will go in

Rectangle used to show action


Oval used to show beginning
Circles used as connectors
Diamonds used as decisions

Combination of control structures

Stacking
Placing one after another
Nesting
Inserting of one structure into another

2002 Prentice Hall. All rights reserved.

4.4 Control Structures

Fig. 4.1

add grade to total

total = total + grade;

add 1 to counter

counter = counter + 1;

Flowcharting C#s sequence structure.

2002 Prentice Hall. All rights reserved.

4.4 Control Structures


C# Keywords

abstract
byte
class
delegate
event
fixed
goto
interface
namespace
out
public
sealed
static
throw
ulong
value

Fig. 4.2

as
case
const
do
explicit
float
if
internal
new
override
readonly
set
string
true
unchecked
virtual

C# keywords.

2002 Prentice Hall. All rights reserved.

base
catch
continue
double
extern
for
implicit
is
null
params
ref
short
struct
try
unsafe
void

bool
char
decimal
else
false
foreach
in
lock
object
private
return
sizeof
switch
typeof
ushort
volatile

break
checked
default
enum
finally
get
int
long
operator
protected
sbyte
stackalloc
this
uint
using
while

4.5 if Selection Structure


The if structure
Causes the program to make a selection
Chooses based on conditional
Any expression that evaluates to a bool type
True: perform an action
False: skip the action

Single entry/exit point


Require no semicolon in syntax

2002 Prentice Hall. All rights reserved.

10

4.5 if Selection Structure

true
Grade >= 60

print Passed

false

Fig. 4.3

Flowcharting a single-selection if structure.

2002 Prentice Hall. All rights reserved.

11

4.6 if/else selection structure


The if/else structure

Alternate courses can be taken when the statement is false


Rather than one action there are two choices
Nested structures can test many cases
Structures with many lines of code need braces ({)

Can cause errors


Fatal logic error
Nonfatal logic error

2002 Prentice Hall. All rights reserved.

12

4.6 if/else Selection Structure

false

true
Grade >= 60

print Failed

Fig. 4.4

Flowcharting a double-selection if/else structure.

2002 Prentice Hall. All rights reserved.

print Passed

13

Conditional Operator (?:)


Conditional Operator (?:)
C#s only ternary operator
Similar to an if/else structure
The syntax is:

(boolean value ? if true : if false)

2002 Prentice Hall. All rights reserved.

14

4.7 while Repetition Structure


Repetition Structure
An action is to be repeated
Continues while statement is true
Ends when statement is false

Contain either a line or a body of code

Must alter conditional


Endless loop

2002 Prentice Hall. All rights reserved.

15

4.7 while Repetition Structure

true
Product <= 1000

Product = 2 * product

false

Fig. 4.5

Flowcharting the while repetition structure.

2002 Prentice Hall. All rights reserved.

4.8 Formulating Algorithms: Case Study 1


(Counter Controlled Repetition)
Counter Controlled Repetition
Used to enter data one at a time
Constant amount

A counter is used to determine when the loop should break


When counter hits certain value, the statement terminates

2002 Prentice Hall. All rights reserved.

16

4.8 Formulating Algorithms: Case Study 1


(Counter Controlled Repetition)
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average

Fig. 4.6 Pseudocode algorithm that uses counter-controlled repetition to solve the classaverage problem.
2002 Prentice Hall. All rights reserved.

17

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

Outline

// Fig. 4.7: Average1.cs


// Class average with counter-controlled repetition.
using System;

Average1.cs

class Average1
{
static void Main( string[] args )
{
int total,
// sum of grades
gradeCounter,
// numberInitialize
of grades
entered
total
to 0
gradeValue,
// grade value
average;
// average of all grades

Initialize gradeCounter to 1

// initialization phase
total = 0;
// clear total
gradeCounter = 1;
// prepare to loop
The

while loop will loop through 10


times to get the grades of the 10 students

// processing phase
while ( gradeCounter <= 10 ) // loop 10 times
{
// prompt for input and read grade from user
Console.Write( "Enter integer grade: " );

Prompt the user to enter a grade

// read input and convert to integer


gradeValue = Int32.Parse( Console.ReadLine() );

Accumulate the total of the 10 grades

// add gradeValue to total


total = total + gradeValue;

Add 1 to the counter so the loop will eventually end

// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;
}

2002 Prentice Hall.


All rights reserved.

18

34
35
36
37
38
39
40
41
42
43

// termination phase
average = total / 10;

Outline
// integer division

// display average of exam grades


Console.WriteLine( "\nClass average is {0}", average );
} // end Main
} // end class Average1

Average1.cs

Divide the total by ten to get


the average of the ten grades
Display the results

Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

integer
integer
integer
integer
integer
integer
integer
integer
integer
integer

grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:

100
88
93
55
68
77
83
95
73
62

Program Output

Class average is 79

2002 Prentice Hall.


All rights reserved.

19

4.9 Formulating Algorithms with Top-Down,


Stepwise Refinement: Case Study 2 (Sentinel
Controlled Repetition)
Sentinel controlled repetition
Continues an arbitrary amount of times
Sentinel value
Causes loop to break
Avoid collisions
When flag value = user entered value

Creating pseudocode
Start with one task
Break it into several tasks
Continue breaking until each task is simple

Casting

Allows one variable to temporarily be used as another


2002 Prentice Hall. All rights reserved.

20

4.9 Formulating Algorithms with Top-Down,


Stepwise Refinement: Case Study 2 (Sentinel
Controlled Repetition)
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print No grades were entered

Fig. 4.8 Pseudocode algorithm that uses sentinel-controlled repetition to solve the classaverage problem.
2002 Prentice Hall. All rights reserved.

21

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Outline

// Fig. 4.9: Average2.cs


// Class average with sentinel-controlled repetition.
using System;

Average2.cs

class Average2
{
static void Main( string[]
{
int total,
//
gradeCounter,
//
gradeValue;
//
double average;

args )
sum of grades
The variable average is set to a
number of grades entered
double so that it can be more exact
grade value

and have an answer with decimals

// average of all grades

// initialization phase
total = 0;
// clear total
gradeCounter = 0;
// prepare to loop

Variables gradeCounter and total are


set to zero at the beginning

// processing phase
// prompt for input and convert to integer
Console.Write( "Enter Integer Grade, -1 to Quit: " );
gradeValue = Int32.Parse( Console.ReadLine() );

Get a value from the user and


store it in gradeValue

2002 Prentice Hall.


All rights reserved.

22

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

Outline

// loop until a -1 is entered by user


while ( gradeValue != -1 )
{
Have the program loop as
// add gradeValue to total
total = total + gradeValue;
long as gradeValue is not -1

23

Average2.cs
Accumulate the total of the grades

// add 1 to gradeCounter
gradeCounter = gradeCounter + 1;

Add 1 to the counter in order


to know the student count

// prompt for input and read grade from user


// convert grade from string to integer
Console.Write( "Enter Integer Grade, -1 to Quit: " );
gradeValue = Int32.Parse( Console.ReadLine() );
} // end while
// termination phase
if ( gradeCounter != 0 )
{
average = ( double ) total / gradeCounter;

Prompt the user for another


grade, this time it is in the loop so
it can happen repeatedly

// display average of exam grades


Console.WriteLine( "\nClass average is {0}", average );
}
else
{
Console.WriteLine( "\nNo grades were entered" );
}
} // end method Main
} // end class Average2

Inform user if no grades


were entered

Makethe
sure
theby
total
Divide
total
theamount
number
of
entered
grades
was
not
of times the program looped
to zero
find to
theprevent
averageany errors

Display the average

2002 Prentice Hall.


All rights reserved.

Enter
Enter
Enter
Enter

Integer
Integer
Integer
Integer

Grade,
Grade,
Grade,
Grade,

-1
-1
-1
-1

to
to
to
to

Quit:
Quit:
Quit:
Quit:

Class average is 85.6666666666667

97
88
72
-1

Outline
Average2.cs
Program Output

2002 Prentice Hall.


All rights reserved.

24

4.10 Formulating Algorithms with Top-Down,


Stepwise Refinement: Case Study 3 (Nested
Control Structures)
Nesting
The insertion of one control structure inside another

Multiple loops
Loops with if statements

2002 Prentice Hall. All rights reserved.

25

4.10 Formulating Algorithms with Top-Down,


Stepwise Refinement: Case Study 3 (Nested
Control Structures)
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. 4.10 Pseudocode for examination-results problem.

2002 Prentice Hall. All rights reserved.

26

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

Outline

// Fig. 4.11: Analysis.cs


// Analysis of Examination Results.
using System;

Analysis.cs

class Analysis
{
static void Main( string[] args )
{
Initialize both passes and failures
int passes = 0,
// number of passes
Set the student count to 1
failures = 0,
// number of failures
student = 1,
// student counter
result;
// one exam result

to 0

A while loop that will loop 10 times

// process 10 students; counter-controlled loop


while ( student <= 10 )
{
Console.Write( "Enter result (1=pass, 2=fail): " );
result = Int32.Parse( Console.ReadLine() );
if ( result == 1 )
passes = passes + 1;
else
failures = failures + 1;

A nested if statement that determines


which counter should be added to
If the user enters 1
add one to passes

student = student + 1;
}

If the user enters 2 then add one to failures


Keep track of the total number of students

2002 Prentice Hall.


All rights reserved.

27

30
31
32
33
34
35
36
37
38
39
40

Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

// termination phase
Console.WriteLine();
Console.WriteLine( "Passed: " + passes );
Console.WriteLine( "Failed: " + failures );
if ( passes > 8 )
Console.WriteLine( "Raise Tuition\n" );

Outline
Analysis.cs
Display the results to the user

} // end of method Main


} // end of class Analysis

result
result
result
result
result
result
result
result
result
result

(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,

2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):

1
2
1
1
1
1
1
1
1
1

If the total number of passes was greater than


8 then also tell the user to raise the tuition

Program Output

Passed: 9
Failed: 1
Raise Tuition

2002 Prentice Hall.


All rights reserved.

28

Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter

result
result
result
result
result
result
result
result
result
result

(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,
(1=pass,

2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):
2=fail):

1
2
2
2
2
2
1
1
1
1

Outline
Analysis.cs
Program Output

Passed: 5
Failed: 5

2002 Prentice Hall.


All rights reserved.

29

30

4.11 Assignment Operators


Assignment operators
Can reduce code
x += 2 is the same as x = x + 2

Can be done with all the math operators

++, -=, *=, /=, and %=

2002 Prentice Hall. All rights reserved.

31

4.11 Assignment Operators


Assignment operator

Sample expression

Explanation

+=
-=
*=
/=
%=

c
d
e
f
g

c
d
e
f
g

Assume: int c = 3,
d = 5, e = 4, f =
6, g = 12;

+=
-=
*=
/=
%=

7
4
5
3
9

Fig. 4.12 Arithmetic assignment operators.

2002 Prentice Hall. All rights reserved.

Assigns

=
=
=
=
=

c
d
e
f
g

+
*
/
%

7
4
5
3
9

10 to c
1 to d
20 to e
2 to f
3 to g

32

4.12 Increment and Decrement Operators


Increment operator
Used to add one to the variable
x++
Same as x = x + 1

Decrement operator
Used to subtract 1 from the variable
y--

Pre-increment vs. post-increment


x++ or x- Will perform an action and then add to or subtract one from the
value

++x or --x

Will add to or subtract one from the value and then perform an
action
2002 Prentice Hall. All rights reserved.

33

4.12 Increment and Decrement Operators


Operator

Called

Sample expression

Explanation

++

postincrement

a++

Use the current value of a in the expression


in which a resides, then increment a by 1.

--

predecrement

--b

Decrement b by 1, then use the new value


of b in the expression in which b resides.

--

postdecrement

b--

Use the current value of b in the expression


in which b resides, then decrement b by 1.

++

preincrement

++a

Increment a by 1, then use the new value


of a in the expression in which a resides.

Fig. 4.13 The increment and decrement operators.

2002 Prentice Hall. All rights reserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
5
5
6
5
6
6

Outline

// Fig. 4.14: Increment.cs


// Preincrementing and postincrementing
using System;

Increment.cs

class Increment
{
static void Main(string[] args)
{
int c;

Declare variable c
Set c equal
Display
c (5) to 5

c = 5;
Console.WriteLine( c );
// print 5
Console.WriteLine( c++ ); // print 5 then
postincrement
Display
c (5) then add
Console.WriteLine( c );
// print 6
Console.WriteLine();

Display c (6)

// skip a line

c = 5;
Console.WriteLine( c );
// print c5 is set to 5 Display c (5)
Console.WriteLine( ++c ); // preincrement then print 6
Console.WriteLine( c );
// print 6 Add 1 then display c (6)
} // end of method Main

Display c (6)

} // end of class Increment

Program Output

2002 Prentice Hall.


All rights reserved.

34

35

4.12 Increment and Decrement Operators


Operators

()
++ -++ -- + - (type)
* / %
+ < <= > >=
== !=
?:
= += -= *= /= %=

Associativity

Type

right to left

unary prefix

left to right

multiplicative

left to right

additive

left to right

relational

left to right

equality

right to left

conditional

right to left

assignment

left to right
right to left

parentheses
unary postfix

Fig. 4.15 Precedence and associativity of the operators discussed so far in this

book.

2002 Prentice Hall. All rights reserved.

4.13 Introduction to Windows Application


Programming
Inheritance
Base class
a class from which another class inherits from

Derived class
The class from which another class inherits

Classes inherit basics of a class


Attributes (data)
Behaviors (methods)

Prevents the continual rewriting of code

2002 Prentice Hall. All rights reserved.

36

4.13 Introduction to Windows Application


Programming

Collapsed
comment
Collapsed
code

Fig. 4.16 IDE showing program code for Fig. 2.15.

2002 Prentice Hall. All rights reserved.

37

4.13 Introduction to Windows Application


Programming

38

Expanded code

Fig. 4.17 Windows Form Designer generated code when expanded.

2002 Prentice Hall. All rights reserved.

4.13 Introduction to Windows Application


Programming
Click here for
code view
Click here for
design view

Fig. 4.18 Code generated by the IDE for welcomeLabel.

2002 Prentice Hall. All rights reserved.

39

Property initializations
for WelcomeLabel

4.13 Introduction to Windows Application


Programming

Text property

Fig. 4.19 Using the Properties window to set a property value.

2002 Prentice Hall. All rights reserved.

40

4.13 Introduction to Windows Application


Programming

Fig. 4.20 Windows Form Designer generated code reflecting new property values.

2002 Prentice Hall. All rights reserved.

41

4.13 Introduction to Windows Application


Programming

Text property

Fig. 4.21 Changing a property in the code view editor.

2002 Prentice Hall. All rights reserved.

42

4.13 Introduction to Windows Application


Programming
Text property value

Fig. 4.22 New Text property value reflected in design mode.

2002 Prentice Hall. All rights reserved.

43

4.13 Introduction to Windows Application


Programming
ASimpleProgram_Load method

Fig. 4.23 Method ASimpleProgram_Load.

2002 Prentice Hall. All rights reserved.

44

4.13 Introduction to Windows Application


Programming

Fig. 4.24 Changing a property value at runtime.

2002 Prentice Hall. All rights reserved.

45

Anda mungkin juga menyukai