L07 ControlLoops
L07 ControlLoops
• while Loops
• do while Loops
• for Loops
• break Statement
• continue Statement
CS 160, Spring Semester 2015 2
int count = 1;
int
count
=
1;
Code begins
int sum = 0;
while (count < 5)
int
sum
=
0;
{ while
(count
<
5)
count = 1, sum = 0
{
False,
True
true, again,
enter
exit loop
loop
sum += count;
(count
re-enter5,loop
sum 10)
count++;
sum
+=
count;
}
count++;
}
Bottom of loop:
What exactly does this code do?
count = 5,
2, sum = 10
3,
4, 1
3
6
1
More
formally: while
Loops
Echo
Example
Program
import
java.u3l.Scanner;
while (condition)
body public
class
Foo
{
• Repeatedly
executes
as
long
as
the
condition
public
sta3c
void
main(String[]
args)
{
Scanner
in_str
=
new
Scanner(System.in);
evaluates
to
true
String
user_string
=
in_str.next();
• body
of
the
loop
is
a
single
statement or
while
(!user_string.equals("quit"))
{
mulIple
statements
within
{
}
System.out.println(user_string);
user_string
=
in_str.next();
• The
condiIon
is
tested
before
the
body
is
}
executed,
so
loop
may
execute
zero
Imes
}
– This
is
called
a
pre-‐test
loop
}
CS 160, Spring Semester 2015 5 CS 160, Spring Semester 2015 6
2
Warning!
What
if
my
program
gets
caught
in
an
infinite
loop?
• An
infinite
loop
will
occur
if
the
condiIon
never
• You
will
need
to
kill
your
program
becomes
false.
– This
is
operaIng
system
specific
• Example:
• Make
your
life
easier:
run
your
program
in
int count = 1;
int sum = 0; count
the
debugger!
never gets
while (count <= 5) updated –
– In
Eclipse,
select
“debug”
instead
of
“run”.
{ always = 1 – It
will
offer
to
take
you
to
the
debug
view.
sum += count;
– Use
the
red
buaon
to
kill
the
program.
}
– Benefit:
Run
program
step-‐by-‐step
(F5).
CS 160, Spring Semester 2015 9 CS 160, Spring Semester 2015 10
3
Notes
on
divisor
example
(2)
Divisor
example
quesIons
4
Remove
Vowels:
QuesIons
for
Loop
• If
the
input
is
“Programming”:
• It
is
common
to
iterate
counter
number
of
– How
many
Imes
will
the
loop
body
execute?
Imes.
• 11
– counter
might
be
a
numeric
bound
– What
will
the
output
be?
• As
in
the
divisor
example
• Prgrmmng
• If
the
input
is
“Java”:
– counter
might
be
the
length
of
a
string
or
array
– How
many
Imes
will
the
loop
body
execute?
• As
in
the
remove
vowels
example
• Exercise
• A
for
loop
gives
you
a
mechanism
to
specify
– What
will
the
output
be?
• Exercise
this
explicitly
CS 160, Spring Semester 2015 17 CS 160, Spring Semester 2015 18
5
Example
Mapping
between
for
and
while
• while
loop
version
int sum = 0;
initialization;
for(int count=1; count <= 5; count++) while (condition)
sum +=count; {
statement;
update;
}
• for
loop
version
for (initialization; condition; update )
statement;
6
Variants
on
the
for
Loop
do while
Statement
1
2
• MulIple
variables
in
for
loop
3
4
do
int
x
=
1;
5 {
for(
int
lo
=
0,
hi
=
10;
lo
<
hi;
lo++,
hi-‐-‐)
body
System.out.println(
x++
);
} while (condition);
• Not
all
parts
to
the
for
loop
• post-‐test
loop:
always
executes
the
loop
body
at
least
once
String
s
=
“Javarules”;
• Executes
again
as
long
as
its
condiIon
is
true
int
i
=
s.length(
)
–
1;
seluravaJ • {
}
are
required
for ( ; i>=0; ) • ;
required
aTer
while
System.out.print( s.charAt(i--) );
CS 160, Spring Semester 2015 25 CS 160, Spring Semester 2015 26
7
Which
loop
to
use?
Problem
Solving
and
FormulaIng
Loops
• Stepwise
Development:
if
(
you
know
the
#
of
iteraIons
)
– Break
problem
into
subparts
– use
a
for
loop
– IdenIfy
repeaIng
paaern
in
problem
formulaIon
else
if
(
statements
should
be
done
at
least
once
)
– Put
paaern
into
body
of
loop
– use
a
do…while
loop
– IdenIfy
a
conInuing
condiIon
(or
terminaIon
condiIon)
else
– Make
separate
loops
when
mulIple
paaerns
are
found
– use
a
while
loop
– Make
nested
loops
when
one
paaern
fits
within
another
8
In
other
words
…
Nested
Loops
• Stepwise
refinement
• Write
the
code
to
print
out
the
following:
– don’t
do
everything
at
once
*
** ALGORITHM
– idenIfy
sub-‐tasks
and
work
on
one
at
the
Ime
*** OUTER LOOP: 10 times (10 rows)
• IdenIfy
loop
paaerns
**** INNER LOOP: 1 to outer loop counter
– the
repeated
behavior
***** print *
****** go to next line
– what
is
to
be
done
before
the
loop
*******
•
e.g.,
iniIalizaIon
********
– how
is
loop
terminaIon
decided
*********
– what
needs
to
be
done
aTer
the
loop
**********
•
e.g.,
store
or
print
results
CS 160, Spring Semester 2015 33 CS 160, Spring Semester 2015 34
public class Stars • Ensure
that
the
required
precision
of
your
condiIon
matches
{ that
of
the
type
public static void main(String[] args) • Recall
that
two
doubles
may
be
mathema5cally
equal
but
not
{ in
the
computer!
for( int c = 1; c <= 10; c++ ) • Use
{
}
for
mulIple
statements
{
for( int i = 0; i < c; i++ ) • Check
for
off-‐by-‐1
errors,
most
importantly
make
sure
that
{ loop
ends
at
the
right
Ime)
System.out.print( '*' ); • Do
NOT
put
a
‘;’
at
the
end
of
a
for(
)
or
while(
)
statement!!!
}
System.out.println( ); • In
a
while
loop,
the
condiIon
must
be
testable
prior
to
} execuIng
the
body
} Why do we have • In
any
loop,
ensure
that
the
update
will
eventually
cause
} an empty println ? cause
the
condiIon
to
become
false
CS 160, Spring Semester 2015 35 CS 160, Spring Semester 2015 36
9
CauIons
about
Loops
CauIons
about
Loops
• Check
for
off-‐by-‐1
errors
(make
sure
that
it
is
ending
at
the
• Do
NOT
put
a
;
at
the
end
of
a
for(
)
or
while(
)
!!!
right
Ime)
Declares
an
empty
body
for
the
loop.
Therefore
the
statements
you
think
are
in
the
body
of
the
loop
actually
aren’t
for ( int i=1; i<100; i++ )
{
for ( int i=0; i<100; i++ );
System.out.print( “*” );
{
}
System.out.print( “*” );
Prints 99 stars. }
Why? Prints ONE star!
Why?
CS 160, Spring Semester 2015 37 CS 160, Spring Semester 2015 38
• Infinite
Loops:
loop
with
a
condiIonal
that
• Run
your
loops
by
hand
(pencil
and
paper)
never
becomes
false:
– Write
out
expectaIons,
check
them
if
need
be
• Don’t
use
break
and
continue
in
loops
– They
get
very
confusing
very
fast
while(
true
)
for
(int
i=1;
i>0;
i++
)
computeSquares();
processOutput(
);
• Echo
values
of
variables
System.out.println(“Str: “ + Str);
• Use
useful
idenIfiers
– no
one-‐leaer
idenIfiers,
except
for
loop
indices
x
=
1;
y
=
1;
• Declare
variables
in
the
right
scope
while(
x
<
10
);
while(
y
<
10
)
– OTen
at
top
of
scope
is
good
x
=
x
+
5;
System.out.print(
y
);
• Give
yourself
a
chance
to
succeed
y++;
– Don’t
start
your
project
on
day
before
the
deadline
10
Loop
PracIce
Problems
11