Download Java Programming, Second edition

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
IT259 Foundation of
Programming Using Java
Unit 7 Seminar :
(Chapter 6 )
Instructor : Vladimir Gubanov, PhD
Email : [email protected]
A reminder:
1.
2.
3.
Our Seminars :
they will be each Thursday , from 9
PM to 10 PM EST
My Office Hours :
Mondays, 7PM to 8PM
Saturdays, 9AM to 10 AM
My email :
[email protected]
Java Programming,
Fifth Edition
Chapter Six:
Looping
Objectives
•
Use a while loop
•
Use shortcut arithmetic operators
Use a for loop
How and when to use a do...while loop
•
•
•
•
Nested loops
Improving loop performance
Java Programming, Fifth
Edition
4
Repetition Structure
(the last control structure in Java,
what are the other two ?)
1- 5
© 2001 by The McGraw-Hill Companies, Inc. All rights reserved.
Java Loop Structures
•
•
•
Repeating a series of instructions
Each repetition is called an iteration
Three types of loops
– while
• Loop-controlling Boolean expression is the first
statement
– for
• A concise format in which to execute loops
– do...while
• Loop-controlling Boolean expression is the last
statement
Java Programming, Fifth
Edition
6
Learning About the Loop Structure
Java Programming, Fifth
Edition
7
while Loop
•
while loop
– Executes body of statements continually
• As long as Boolean expression that controls
entry into loop continues to be true
– Consists of keyword while
• Followed by Boolean expression within
parentheses
• Followed by body of loop; can be single
statement or block of statements surrounded
by curly braces
Java Programming, Fifth
Edition
8
Using a while Loop To Create
a Definite Loop
What will happen if the second line in the
loop body will be removed ?
Java Programming, Fifth
Edition
9
Using a while Loop To Create a Definite
Loop
•
•
•
•
Definite loop
– Performs task a predetermined number of times
Write a definite loop
– Initialize loop control variable
• Variable whose value determines whether loop
execution continues
– While loop control variable does not pass limiting value
• Program continues to execute body of while loop
Write body of loop
• Must include statement that alters loop control
variable
Infinite loop ? When will10it happen ?
Java Programming, Fifth
Edition
Using a while Loop
NNNN
How many iterations will be executed ?
Java Programming, Fifth
Edition
11
Using a while Loop To Create
a Definite Loop
•
Prevent while loop from executing infinitely
– Named loop control variable initialized to
starting value
– Loop control variable tested in while statement
– If test expression true
• Body of while statement takes action
– Alters value of loop control variable
• Test of while statement must eventually
evaluate to false
Java Programming, Fifth
Edition
12
Using a while Loop To Create
a Definite Loop
Is there any error here ?
Java Programming, Fifth
Edition
13
NNN
Is there any error here ?
Java Programming, Fifth
Edition
14
Using a while Loop To Create
a Definite Loop
•
•
•
Increment variable
– Alter value of loop control variable by adding 1
(or any other reasonable value)
Decrement variable
– Subtract 1 ( or any other reasonable value)
from loop control variable
Clearest and best method
– Start loop control variable at 0 or 1
– Stop when loop control variable reaches limit
– Increment by 1 each time through loop
Java Programming, Fifth
Edition
15
Using a while Loop To Create
a Definite Loop
How many times will this loop execute ? What will be
the value of loopCount when the loop breaks ?
Java Programming, Fifth
Edition
16
How may iterations will
this loop perform ?
17
Java Programming, Fifth
Edition
Using Shortcut Arithmetic Operators
•
•
Accumulating
– Repeatedly increasing value by some
amount
Java provides shortcuts for incrementing
and accumulating:
+= add and assign
-= subtract and assign
*= multiply and assign
/= divide and assign
%= remainder and assign
Java Programming, Fifth
Edition
18
Using Shortcut Arithmetic Operators
•
Prefix and postfix increment operators
++someValue, someValue++
– Use only with variables
– Unary operators
• Use with one value
– Increase variable’s value by 1
• No difference between operators (unless
other operations in same expression)
Java Programming, Fifth
Edition
19
Using Shortcut Arithmetic Operators
Java Programming, Fifth
Edition
20
Using Shortcut Arithmetic Operators
•
•
Prefix and postfix increment operators
– Prefix ++
• Result calculated and stored
• Then variable used
– Postfix ++
• Variable used
• Then result calculated and stored
Prefix and postfix decrement operators
--someValue
someValue-– Similar logic to increment operators
Java Programming, Fifth
Edition
21
Using a for Loop
•
for Loop
– Used when definite number of loop
iterations is required
– One convenient statement
• Assign starting value for loop control
variable
• Test condition that controls loop entry
• Alter loop control variable
Java Programming, Fifth
Edition
22
for Loop Flow Chart
23
Using a for Loop
What will be the results of processing of each of the
loops above ?
Java Programming, Fifth
Edition
24
Using a for Loop
•
Other uses for three sections of for loop
– Initialization of more than one variable
• Place commas between separate statements
– Performance of more than one test using AND or
OR operators
– Decrementation or performance of some other task
– Altering more than one value
– Can leave one or more portions of for loop
empty
• Two semicolons still required as placeholders
• Use same loop control variable in all three parts of
for statement
Java Programming, Fifth
25
Edition
for Loop Example
For loop is executed as
shown in the numbered
steps
System.out.println(I + “\t”);
System.out.println(“”n” + “Finished”);
Why don’t you have curly braces here ? Where to place those
if needed ?
26
do…while Statements
•
Posttest : condition
continue looping or not is
tested after the loop body
is executed
•
General form:
do
{
statement;
}
while( conditional
expression);
27
How and When to Use a do...while
Loop
•
do...while loop
– Posttest loop
– Checks value of loop control variable
• At bottom of loop
• After one repetition has occurred
– Performs task at least one time
– Never required to use this type of loop
– Use curly brackets to block statement
• Even with single statement
Java Programming, Fifth
Edition
28
a do...while Loop
Java Programming, Fifth
Edition
29
How and When to Use a
do...while Loop
How many times will this loop execute ?
Java Programming, Fifth
Edition
30
Another do…while Example
int counter = 10;
do
// No semicolon on this line
{
System.out.writeln(counter + "\t" + math.pow(counter, 2));
counter--;
}
while (counter > 6);
What values of
counter variable will
this loop print ?
Change this loop in order it
would print 7 numbers.
Type your answer.
31
Nested Loops
•
Inner and outer loops
– Inner loop must be entirely contained in
outer loop
– Loops can never overlap
•
To print mailing labels for customers :
for(customer = 1; customer <= 20;
++customer)
for(label = 1; label <= 3; ++label)
printLabelMethod();
How many mailing labels will be printed ?
Java Programming, Fifth
Edition
32
Nested Loops (continued)
Java Programming, Fifth
Edition
33
Improving Loop Performance
•
•
•
Make sure loop does not include
unnecessary operations or
statements
Consider order of evaluation for
short-circuit operators
Make comparisons to 0
Java Programming, Fifth
Edition
34
Avoiding
Unnecessary Operations
• Do not use unnecessary operations or statements:
– Within loop’s tested expression
– Within loop body
•
Avoid
while (x < a + b)
// loop body
•
Instead use
int sum = a + b;
while(x < sum)
// loop body
Why is it better ?
Java Programming, Fifth
Edition
Considering the Order of Evaluation
for Short-Circuit Operators
•
Short-circuit evaluation
– Each part of an AND or an OR
expression is evaluated only as much as
necessary to determine the value of
expression
•
Important to consider number of
evaluations that take place
– When loop might execute many times
Java Programming, Fifth
Edition
36
Comparing to Zero
•
Making comparison to 0
– Faster than making comparison to any
other value
•
Improve loop performance
– Compare loop control variable to 0
•
Do not code Do-nothing loop
– Performs no actions other than looping
Java Programming, Fifth
Edition
37
Comparing to Zero
Code and run this loop ( in the textbook ) : compare
Java Programming, Fifth
38
their
relative
speed
Edition
Employing Loop Fusion
•
Loop fusion
– Technique of combining two loops into
one
– Will not work in every situation
Java Programming, Fifth
Edition
39
Summary
•
Loop structure allows repeated
execution of block of statements
– Infinite loop
– Definite loop
– Nest loop
•
•
Must change loop control variable
within looping structure
Use while loop to:
– Execute statements while some
condition
is true
Java Programming,
Fifth
40
Edition
Summary (continued)
•
Execute while loop
– Initialize loop control variable, test in while
statement, and alter loop control variable
•
Prefix ++ and postfix ++
– Increase variable’s value by 1
– Variable used
• Result calculated and stored
•
Unary operators
– Use with one value
Java Programming, Fifth
Edition
41
Summary (continued)
•
Binary operators
– Operate on two values
•
Shortcut operators +=, -=, *=, and /=
– Perform operations and assign result in one
step
•
for loop
– Initializes, tests, and increments in one
statement
•
do...while loop
– Tests Boolean expression after one
Java Programming,
Fifth
42
repetition
Edition
Unconditional Transfer of
Control
•
Break
– Used with Switch statement
– Place in the body of a loop to provide immediate
exit
•
Continue
– When reached, a new iteration of the nearest
enclosing while, do…while, for, or foreach
statement is started
•
Other jump statements
– goto, throw, and return
43
Quiz
• True or False: Within a looping structure, a floating-point expression is
evaluated.
• Answer: False
• A(n) ____ loop is one in which the loop-controlling Boolean
expression is the first statement in the loop.
• Answer: while
• To write a definite loop, you initialize a(n) ____, a variable whose
value determines whether loop execution continues.
• Answer: loop control variable
• A loop controlled by the user is a type of ____ loop because you don’t
know how many times it will eventually loop.
• Answer: indefinite
44
Quiz (cont.)
• The statement count ____1; is identical in meaning to count = count + 1.
• Answer: +=
• The prefix and postfix increment operators are ____ operators because
you use them with one value.
• Answer: unary
• You begin a for loop with the keyword ____ followed by a set of
parentheses.
• Answer: for
• A while loop is a(n) ____ loop—one in which the loop control variable is
tested before the loop body executes.
• Answer: pretest
45
Quiz (cont.)
• The do...while loop is a(n) ____ loop—one in which the loop control
variable is tested after the loop body executes.
• Answer: posttest
• When loops are ____, each pair contains an inner loop and an outer
loop.
• Answer: nested
• True or False: Whether you decide to use a while, for, or do...while
loop in an application, you can improve loop performance by making
sure the loop does not include unnecessary operations or statements.
• Answer: True
• Under what circumstances would you use a for loop rather than a while
loop?
46
Quiz (cont.)
• Why do you think the Java language provides three different types of
loops if all loops can be written using the while statement?
• True or False: Given the for statements form, for (initialization; test;
update), the initialization is performed with each iteration through the
loop.
• Given the following statement, what would be the output produced?
for (int cnt = 0; cnt < 3; cnt++)
System. out.println(cnt) ;
• Used with a loop, how does a continue statement differ from a break
statement?
47
• dialog box
This is the end of our Unit 7
Seminar
•Any questions ?
48