Chapter 4 - Control Structures: Part 1

Download Report

Transcript Chapter 4 - Control Structures: Part 1

1
Chapter 4 - Control Structures: Part 1
 2003 Prentice Hall, Inc. All rights reserved.
2
4.3
Pseudocode
• Pseudocode
– Informal language for developing algorithms
– Not executed on computers
– Helps developers “think out” algorithms
 2003 Prentice Hall, Inc. All rights reserved.
3
4.4
Control Structures
• Sequential execution
– Program statements execute one after the other
• Transfer of control
– Three control statements can specify order of statements
• Sequence structure
• Selection structure
• Repetition structure
• Activity diagram
– Models the workflow
• Action-state symbols
• Transition arrows
 2003 Prentice Hall, Inc. All rights reserved.
4
add grade to total
Corresponding Java statement:
total = total + grade;
add 1 to counter
Corresponding Java statement:
counter = counter + 1;
Fig 4.1 Sequence structure activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
5
4.4
Control Structures
• Java has a sequence structure “built-in”
• Java provides three selection structures
– if
– if…else
– switch
• Java provides three repetition structures
– while
– do…while
– do
• Each of these words is a Java keyword
 2003 Prentice Hall, Inc. All rights reserved.
6
4.5
if Single-Selection Statement
• Single-entry/single-exit control structure
• Perform action only when condition is true
• Action/decision programming model
 2003 Prentice Hall, Inc. All rights reserved.
7
[grade >= 60]
print “Passed”
[grade < 60]
Fig 4.3 if single-selections statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
8
4.6
if…else Selection Statement
• Perform action only when condition is true
• Perform different specified action when condition
is false
• Conditional operator (?:)
max = a > b ? a : b;
• Nested if…else selection structures
 2003 Prentice Hall, Inc. All rights reserved.
9
[grade < 60]
print “Failed”
[grade >= 60]
print “Passed”
Fig 4.4 if…else double-selections statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
10
4.7
while Repetition Statement
• Repeat action while condition remains true
 2003 Prentice Hall, Inc. All rights reserved.
11
merge
decision
[product <= 1000]
double product value
[product > 1000]
Corresponding Java statement:
product = 2 * product;
Fig 4.5 while repetition statement activity diagram.
 2003 Prentice Hall, Inc. All rights reserved.
12
4.8
Formulating Algorithms: Case Study 1
(Counter-Controlled Repetition)
• Counter
– Variable that controls number of times set of statements
executes
• Average1.java calculates grade averages
– uses counters to control repetition
 2003 Prentice Hall, Inc. All rights reserved.
13
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 countercontrolled repetition to solve the class-average
problem.
 2003 Prentice Hall, Inc. All rights reserved.
14
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
// Fig. 4.7: Average1.java
// Class-average program with counter-controlled repetition.
import javax.swing.JOptionPane;
Declare variables;
gradeCounter is the counter
public class Average1 {
public
{
int
int
int
int
static void main( String args[] )
total;
gradeCounter;
grade;
average;
//
//
//
//
sum of grades input by user
number of grade to be entered next
grade value
average of grades Continue looping
String gradeString; // grade typed by
Outline
Average1.java
gradeCounter
Line 21
as long as
gradeCounter is less than or
user
equal to 10
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) {
// loop 10 times
// prompt for input and read grade from user
gradeString = JOptionPane.showInputDialog(
"Enter integer grade: " );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
 2003 Prentice Hall, Inc.
All rights reserved.
15
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
total = total + grade;
gradeCounter = gradeCounter + 1;
// add grade to total
// increment counter
} // end while
Outline
Average1.java
// termination phase
average = total / 10;
// integer division
// display average of exam grades
JOptionPane.showMessageDialog( null, "Class average is " + average,
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate the program
} // end main
} // end class Average1
 2003 Prentice Hall, Inc.
All rights reserved.
16
Outline
Average1.java
 2003 Prentice Hall, Inc.
All rights reserved.
4.9 Formulating Algorithms with TopDown, Stepwise Refinement: Case Study 2
(Sentinel-Controlled Repetition)
• Sentinel value
– Used to indicated the end of data entry
• Average2.java has indefinite repetition
– User enters sentinel value (-1) to end repetition
 2003 Prentice Hall, Inc. All rights reserved.
17
18
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 Class-average problem pseudocode
algorithm with sentinel-controlled repetition.
 2003 Prentice Hall, Inc. All rights reserved.
19
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
// Fig. 4.9: Average2.java
// Class-average program with sentinel-controlled repetition.
import java.text.DecimalFormat; // class to format numbers
import javax.swing.JOptionPane;
Outline
Average2.java
public class Average2 {
public static void main( String args[] )
{
int total;
// sum of grades
int gradeCounter;
// number of grades entered
int grade;
// grade value
double average;
// number with decimal point for average
String gradeString;
// grade typed by user
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
 2003 Prentice Hall, Inc.
All rights reserved.
20
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
57
58
59
// loop until sentinel value read from user
while ( grade != -1 ) {
total = total + grade;
//loop
add until
gradegradeCounter
to total
gradeCounter = gradeCounter + 1; // equals
increment
counter
sentinel
value (-1)
// get next grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
Format numbers to
grade = Integer.parseInt( gradeString ); hundredth
Outline
Average2.java
Line 31
nearest
Line 45
} // end while
// termination phase
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
// if user entered at least one grade...
if ( gradeCounter != 0 ) {
// calculate average of all grades entered
average = (double) total / gradeCounter;
// display average with two digits of precision
JOptionPane.showMessageDialog( null,
"Class average is " + twoDigits.format( average ),
"Class Average", JOptionPane.INFORMATION_MESSAGE );
} // end if part of if...else
 2003 Prentice Hall, Inc.
All rights reserved.
21
60
61
62
63
64
65
66
67
68
else // if no grades entered, output appropriate message
JOptionPane.showMessageDialog( null, "No grades were entered",
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Outline
Average2.java
} // end main
} // end class Average2
 2003 Prentice Hall, Inc.
All rights reserved.
4.10 Formulating Algorithms with TopDown, Stepwise Refinement: Case Study 3
(Nested Control Structures)
• Nested control structures
 2003 Prentice Hall, Inc. All rights reserved.
22
23
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.
 2003 Prentice Hall, Inc. All rights reserved.
24
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
// Fig. 4.11: Analysis.java
// Analysis of examination results.
import javax.swing.JOptionPane;
public class Analysis {
Outline
Loop until student counter is
greater than 10
Analysis.java
Line 19
public static void main( String args[] )
{
// initializing variables in declarations
int passes = 0;
// number of passes
int failures = 0;
// number of failures
int studentCounter = 1; // student counter
int result;
// one exam result
String input;
String output;
// user-entered Nested
value
// output string
Line 29
control structure
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) {
// prompt user for input and obtain value from user
input = JOptionPane.showInputDialog(
"Enter result (1 = pass, 2 = fail)" );
// convert result to int
result = Integer.parseInt( input );
// if result 1, increment passes; if...else nested in while
if ( result == 1 )
passes = passes + 1;
 2003 Prentice Hall, Inc.
All rights reserved.
25
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
else // if result not 1, increment failures
failures = failures + 1;
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
Outline
Analysis.java
} // end while
// termination phase; prepare and display results
output = "Passed: " + passes + "\nFailed: " + failures;
// determine whether more than 8 students passed
if ( passes > 8 )
output = output + "\nRaise Tuition";
JOptionPane.showMessageDialog( null, output,
"Analysis of Examination Results",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class Analysis
 2003 Prentice Hall, Inc.
All rights reserved.
26
4.11 Compound Assignment Operators
• Assignment Operators
– Abbreviate assignment expressions
– Any statement of form
• variable = variable operator expression;
– Can be written as
• variable operator= expression;
– e.g., addition assignment operator +=
•c = c + 3
– can be written as
• c += 3
 2003 Prentice Hall, Inc. All rights reserved.
27
Assig nm ent
Sa m p le
Exp la na tion
op era tor
exp ression
Assume: int c = 3,
d = 5, e = 4, f
= 6, g = 12;
+=
c += 7
c = c + 7
-=
d -= 4
d = d - 4
*=
e *= 5
e = e * 5
/=
f /= 3
f = f / 3
%=
g %= 9
g = g % 9
Fig. 4.12 Arithm etic a ssig nm ent op era to rs.
 2003 Prentice Hall, Inc. All rights reserved.
Assig ns
10 to c
1 to d
20 to e
2 to f
3 to g
28
4.12 Increment and Decrement Operators
• Unary increment operator (++)
– Increment variable’s value by 1
• Unary decrement operator (--)
– Decrement variable’s value by 1
• Preincrement / predecrement operator
• Post-increment / post-decrement operator
 2003 Prentice Hall, Inc. All rights reserved.
29
Op era tor Ca lled
++
preincrement
++
postincrement
--
predecrement
--
postdecrement
Fig. 4.13 The inc rem ent
 2003 Prentice Hall, Inc. All rights reserved.
Sa m p le
exp ression
++a
Exp la na tion
Increment a by 1, then use the new
value of a in the expression in
which a resides.
a++
Use the current value of a in the
expression in which a resides, then
increment a by 1.
--b
Decrement b by 1, then use the
new value of b in the expression in
which b resides.
b-Use the current value of b in the
expression in which b resides, then
decrement b by 1.
a nd d ec re m ent op era tors.
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
30
// Fig. 4.14: Increment.java
// Preincrementing and postincrementing operators.
public class Increment {
Outline
Line 13 postincrements c
public static void main( String args[] )
{
int c;
// demonstrate postincrement
c = 5;
//
System.out.println( c );
//
System.out.println( c++ ); //
System.out.println( c );
//
System.out.println();
assign 5 to c
print 5 Line 21 preincrements
print 5 then postincrement
print 6
Increment.java
Line 13 postincrement
Line 21 preincrement
c
// skip a line
// demonstrate preincrement
c = 5;
//
System.out.println( c );
//
System.out.println( ++c ); //
System.out.println( c );
//
assign 5 to c
print 5
preincrement then print 6
print 6
} // end main
} // end class Increment
5
5
6
5
6
6
 2003 Prentice Hall, Inc.
All rights reserved.
31
Op era tors
Assoc ia tivity
Typ e
++ -right to left
unary postfix
++ -- +
(type)
right to left
unary
*
/
%
left to right
multiplicative
+
left to right
additive
<
<= >
>=
left to right
relational
== !=
left to right
equality
?:
right to left
conditional
=
+= -= *= /= %=
right to left
assignment
Fig. 4.15 Prec ed enc e a nd a ssoc ia tivity of the op era tors d isc ussed so fa r.
 2003 Prentice Hall, Inc. All rights reserved.
32
4.13 Primitive Types
• Primitive types
– “building blocks” for more complicated types
• Java is strongly typed
– All variables in a Java program must have a type
• Java primitive types
– portable across computer platforms that support Java
 2003 Prentice Hall, Inc. All rights reserved.
33
Typ e
boolean
Size in b its
char
16
byte
8
short
16
int
32
long
64
float
32
double
64
Fig. 4.16 The Ja va
Va lues
true or false
Sta nd a rd
[Note: The representation of a boolean is
specific to the Java Virtual Machine on each
computer platform.]
'\u0000' to '\uFFFF'
(ISO Unicode character set)
(0 to 65535)
–128 to +127
(–27 to 27 – 1)
–32,768 to +32,767
(–215 to 215 – 1)
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
Negative range:
(IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
Negative range:
(IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
p rim itive typ es.
 2003 Prentice Hall, Inc. All rights reserved.