CIS 120 CHAPTER 4
PROBLEM SOLVING AND CONTROL
STRUCTURES I
1.
Terms
·
algorithm: finite set of instructions clearly written which eventually
terminate producing desired output.
·
Pseudocode: English-like statements that resemble programming language
syntax. Intention is to make conversion
to actual code easier.
·
Step-wise refinement: iterative process of decomposition of abstract problem
·
Abstraction: looking at the problem as a whole, sum of its part, rather than
as individual components.
2.
Control Structures
·
Sequence
·
Selection
·
Repetition
3.
Flow Chart Symbols for the
control structures.
4.
Selection
if
if else
multiple selection
?:
(conditional operator, {ternary (3
operands) operator})
Boolean expression?: true
action : false action;
System.out.println(grade >= 60 ?:
“Passed” : “Failed”);
Dangling else
problem: occurs in a nested if
statement where the outer if has an else and the inner if does not. The else component binds with the closest
if.
5.
While structure
Example 1
int
product = 2;
while
(product <= 1000)
product
= 2 * product;
Example
2: Counter controlled
String
grade;
int total = 0;
int gradeValue;
int counter = 1;
while
(counter <= 10)
{ grade = JOptionPaneshowInputDialog(“Enter
next grade”);
gradeValue = Integer.parseInt(grade);
total += gradeValue;
counter ++;
}
Example
3: Sentinel controlled and priming read
String grade;
int total = 0;
int gradeValue;
grade = JOptionPaneshowInputDialog(“Enter
next grade”);
gradeValue
= Integer.parseInt(grade);
while
(gradeValue != -1)
{ total += gradeValue;
grade = JOptionPaneshowInputDialog(“Enter next grade”);
gradeValue = Integer.parseInt(grade);
}
6.
DecimatFormal class
DecimatFormal twoDigits;
twoDigits = new DecimalFormat(“0.00”); //at least 1 digit to left of decimal
point,
// exactly 2 digits to the right.
System.out.println(“Average grade =
“ + twoDigits(average));
7.
Note—Study algorithms and
problem solving strategies discussed in Chapter 4.
8.
See Tables in text:
·
Figure
4.12: Arithmetic assignment operators
·
Figure
4.13: Increment and decrement operators
·
Figure
4.15: Precedence table
·
Figure
4.16: Java primitive data types (8)—byte, char, short, int, long, float,
double, Boolean