Chapter 3-eric.pptx

advertisement
Chapter 3
Control
Algorithms and Control Structures
Algorithm: an ordered sequence of precisely defined
instructions that performs some task in a finite amount of
time. Ordered means that the instructions can be
numbered, but an algorithm must have the ability to alter
the order of its instructions using a control structure. There
are three categories of algorithmic operations:
Sequential operations: Instructions executed in order.
Conditional operations: Control structures that first ask a
question to be answered with a true/false answer and then
select the next instruction based on the answer.
Iterative operations (loops): Control structures that repeat
the execution of a block of instructions.
Structured Programming
A technique for designing programs in which a
hierarchy of modules is used, each having a single
entry and a single exit point, and in which control is
passed downward through the structure without
unconditional branches to higher levels of the structure.
In Java these modules can be built-in or user-defined
functions.
Advantages of structured programming
1. Structured programs are easier to write because the programmer can study the
overall problem first and then deal with the details later.
2. Modules (functions) written for one application can be used for other
applications (this is called reusable code).
3. Structured programs are easier to debug because each module is designed to
perform just one task and thus it can be tested separately from the other
modules.
Advantages of structured programming (continued)
4. Structured programming is effective in a teamwork environment because
several people can work on a common program, each person developing one
or more modules.
5. Structured programs are easier to understand and modify, especially if
meaningful names are chosen for the modules and if the documentation
clearly identifies the module’s task.
Steps for developing a computer solution:
1. State the problem concisely.
2. Specify the data to be used by the program. This is the “input.”
3. Specify the information to be generated by the program. This is the “output.”
4. Work through the solution steps by hand or with a calculator; use a simpler set
of data if necessary.
Steps for developing a computer solution (continued)
5. Write and run the program.
6. Check the output of the program with your hand solution.
7. Run the program with your input data and perform a reality check on the
output.
8. If you will use the program as a general tool in the future, test it by running it
for a range of reasonable data values; perform a reality check on the results.
Effective documentation can be accomplished with
the use of
1.
Proper selection of variable names to reflect the
quantities they represent.
2.
Use of comments within the program.
3.
Use of structure charts.
4.
Use of flowcharts.
5. A verbal description of the program, often in
pseudocode.
Documenting with Charts
Two types of charts aid in developing structured
programs and in documenting them.
These are structure charts and flowcharts.
A structure chart is a graphical description showing how
the different parts of the program are connected
together.
Structure chart of a game program.
Flowcharts are useful for developing and
documenting programs that contain conditional
statements, because they can display the various
paths (called “branches”) that a program can take,
depending on how the conditional statements are
executed.
Flowchart representation of
the if statement.
Documenting with Pseudocode
We can document with pseudocode, in which natural
language and mathematical expressions are used to
construct statements that look like computer
statements but without detailed syntax.
Each pseudocode instruction may be numbered, but
should be unambiguous and computable.
There are how many types of
coding operations?
a. 1
b. 2
c. 3
d. 4
e. 5
There are how many types of
coding operations?
Sequential
Conditional
Iterative
Coding challenge!
Sequential operation
Sequential operation
How are you doing with the
programming challenge?
a.
b.
c.
d.
e.
DONE!
Hopelessly lost
Struggling
Haven’t started
Should be able to finish
Development of Large Programs
1.
Writing and testing of individual modules (the unittesting phase).
2. Writing of the top-level program that uses the
modules (the build phase). Not all modules are
included in the initial testing. As the build proceeds,
more modules are included.
4-17
3.
Testing of the first complete program (the alpha release
phase). This is usually done only in-house by technical
people closely involved with the program development.
There might be several alpha releases as bugs are
discovered and removed.
4. Testing of the final alpha release by in-house personnel
and by familiar and trusted outside users, who often
must sign a confidentiality agreement. This is the beta
release phase, and there might be several beta
releases.
4-18
3.1 Blocks, Loops, and Branches
• Blocks
• Multiple statements, delimited by { and }
• Occasionally used on its own, more typically as part of a
statement like class, if, try, or a method
• Interacts with scope of variables
• Typically indented in source code
• Ctl-A (select all) Ctl-I (auto-indent) in Eclipse
• The While loop
• while (boolean expression) {…}
Relational and logical Operators
• Relational operators go between two (usually) numbers
•
•
•
•
•
•
> greater than
>= greater than or equal to
< less than
<= less than or equal to
== equal to
!= not equal to
• Logical operators
• && and
• || or
• ! not As a unary prefix
Basic If statement
• If (boolean expression) {
… // block executed if true
}
else {
… // block executed if false
}
• Blocks are not absolutely
necessary, but cost nothing
and make it easy to add
extra statements
• The else is optional.
Definite assignment
• Can the IDE or Compiler determine if a variable has
been given a value? (assume x is declared and has
a value)
Chained if’s
• If (condition) {
…
} else if (another condition) {
…
} else if (yet another condition) {
…
} else {
…
}
• These provide a very understandable multi-way
choice
try catch
try {
… // if any line generates an exception…
} catch (Exception e) { // we go to the catch block
…
}
This is the simplest version of try… catch, more later.
Conditional Operations
Conditional Operations
3.2 Algorithm development
• What is an algorithm?
• Pseudocode
long names and good structure make real code do
what we used to use pseudocode for.
• flowcharts
• stepwise refinement (top-down design)
3.2.2 Case Study: 3N+1 problem
“Given a positive integer, N, define the ’3N+1’ sequence
starting from N as follows: If N is an even number, then
divide N by two; but if N is odd, then multiply N by 3 and
add 1. Continue to generate numbers in this way until N
becomes equal to 1. For example, starting from N = 3,
which is odd, we multiply by 3 and add 1, giving N =
3*3+1 = 10. Then, since N is even, we divide by 2, giving
N = 10/2 = 5. We continue in this way, stopping when we
reach 1. The complete sequence is: 3, 10, 5, 16, 8, 4, 2, 1.
“Write a program that will read a positive integer from
the user and will print out the 3N+1 sequence starting
from that integer. The program should also count and
print out the number of terms in the sequence.”
Third coding Challenge!
3.2.3 Coding, Testing, Debugging
• Syntax vs semantic errors
• Debugging statements
• IDE debuggers
Syntax errors
• Caught by compiler or IDE
• Usually easy to fix
• Watch out for “easy fixes”
• Matching { and } can be problematic
• Ctl-A, Ctl-I can re-indent in Eclipse to show and
help match up indentations.
Semantic errors
• It does “what you say”, which often isn’t “what you
want”.
• “Probe I/O - putting in “print” statements to trace
where the code goes, and what value variables
have.
• Be sure to label output, or you’ll not know what those
numbers mean.
• Sometimes it is useful to surround probe statements in
IF blocks to only print under certain conditions.
Finding Bugs
Debugging a program is the process of finding and
removing the “bugs,” or errors, in a program. Such
errors usually fall into one of the following categories.
1.
4-14
Syntax errors such as omitting a parenthesis or
comma, or spelling a command name incorrectly.
Eclipse usually detects the more obvious errors and
displays a message describing the error and its
location.
2. Errors due to an incorrect mathematical procedure.
These are called runtime errors. They do not
necessarily occur every time the program is executed;
their occurrence often depends on the particular input
data. A common example is division by zero.
To locate a runtime error, try the following:
1.
Always test your program with a simple version of the
problem, whose answers can be checked by hand
calculations.
2. Display any intermediate calculations by removing
semicolons at the end of statements.
4-15
Probe I/O
Putting in “print” statements to trace where the
code goes, and what value variables have.
• Be sure to label output, or you’ll not know what those
numbers mean.
• Sometimes it is useful to surround probe statements in
IF blocks to only print under certain conditions.
• Printing to the console is common, but sometimes you
may need to print to a window in a GUI
• Often, don’t remove those print statements – enclose
them in a block comment.
IDE Debuggers
• Get to know your debugger!
• It will help you understand how code flows, and
how variables get different values.
• Breakpoints are places where the debugger will
pause and let you see what is going on.
• Eclipse debugger perspective is useful, it
“remembers” a different arrangement of window
panes suitable for debugging.
3.3 while and do … while loops
• while (boolean) {…body…} is a pre-test
loop.
• The body of the loop may never execute
• Something in the body has to change something that is
tested in the boolean expression, or you will get an
Infinite Loop
• do {…body…}while (boolean); is a posttest loop.
• The body will always execute at least once.
• Can be useful for input validation.
break and continue
• Break; immediately jump out of the loop
• Useful for a test in the middle of a loop
• Can cause confusion if too many ways of terminating a
loop. Some purists discourage its use.
• However, works nicely in a while(true) { … }
loop
• continue; immediately jump to the next test
• Less frequently used. There are other ways to do this
• Labeled loops so 20th century! Avoid. There are
cleaner ways to do this.
3.4 the for loop
• Many loops have the form:
<initialization >
while ( <continuation-condition > ) {
<statements >
<update >
}
• for (<initialization >; <continuation-condition > ; <update >) {
<statements >
}
• All in a nice package! (inherited from C)
Loop flowchart
Example: printing even numbers
Four different ways of printing all even numbers from
2 to 20
• Print 2*n
• Increment by 2
• Use if to limit printing to even numbers
• Irritate the professor
Example: looping on chars
• for (char ch='A'; ch <='Z'; ch++)
System.out.print(ch);
}
System.out.println();
Example: Counting divisors
• This example in the book is worth typing in and
playing with.
• Very good user-interface issue: if your program
runs too long without output, the user may suspect
that something is wrong. Never force the user to
wait more than a couple of seconds without seeing
something happening.
Iterative Operations
Iterative Operations
Nested loops
• Loops within loops within loops – it happens all the
time.
• 12X12 multiplication table is a good example
3.5 if, revisited
• Dangling if: read the book, use { and } to clarify
to which if the else belongs.
3.5.2 Multiway branching
• Discussed above as “chained ifs”
• Several good examples in the book
3.5.4 the empty statement
• Legal
• Risky, a superfluous ; can wreak havoc
• Auto-indent can help reveal the problem.
3.6 the switch statement
• Inherited from C, it is an old and clunky syntax
• It can do a multi-way swich, as an alternate to
if …. else if … else if … else
syntax
• It can only switch on primitives, but you can do
anything with else if construction.
3.6 the switch statement
• Can implement menus of options
• You can use enums (but not objects)
• Definite assignment requires a default block
3.7 try … catch
3.8 arrays
• Data structure
• Length
• Base type
• Index
• [] syntax
3.8.2 Arrays and For loops
3.8.3 Random vs Sequential access
3.8.4 Partially filled arrays
3.8.5 two-dimensional arrays
3.9 introduction to GUI
3.9.1 Drawing Shapes
3.9.2 Drawing in a program
3.9.3 Animation
Download