PreludeProgramming6ed pp06
PreludeProgramming6ed pp06
One
reason
to
nest
a
selecJon
structure
inside
a
loop
is
to
allow
the
loop
to
end
before
the
test
condiJon
has
been
met
for
any
reason.
For
example:
ØIf
the
user
has
entered
an
incorrect
value
that
would
cause
an
error
ØIf
the
user
has
entered
a
required
response
and
the
program
can
conJnue
without
further
iteraJons
The
example
in
the
next
slide
shows
how
to
keep
track
of
how
many
posiJve
numbers
and
how
many
negaJve
numbers
are
input
by
a
user.
Uses
for
this
type
of
program:
Ø
Embed
in
a
larger
program
to
track
various
types
of
entries
Ø
Use
by
a
college
to
enter
demographic
informaJon
on
students
Ø
Use
by
a
business
to
track
number
of
items
purchased
that
were
above
or
below
a
certain
cost
If
TheSpace = “ “
then:
Ø MyLength = Length_Of(TheSpace)
assigns
the
value
of
1
to
MyLength because
a
space
counts
as
one
character.
1 + 2 = 3 2 + 2 = 4 3 + 2 = 5 4 + 2 = 6 5 + 2 = 7 6 + 2 = 8
1 + 3 = 4 2 + 3 = 5 3 + 3 = 6 4 + 3 = 7 5 + 3 = 8 6 + 3 = 9
1 + 4 = 5 2 + 4 = 6 3 + 4 = 7 4 + 4 = 8 5 + 4 = 9 6 + 4 = 10
1 + 5 = 6 2 + 5 = 7 3 + 5 = 8 4 + 5 = 9 5 + 5 = 10 6 + 5 = 11
1 + 6 = 7 2 + 6 = 8 3 + 6 = 9 4 + 6 = 10 5 + 6 = 11 6 + 6 = 12
Possible
ways
to
roll
a
5:
(1,4), (4,1), (2,3), (3,2)
Possible ways to roll an 8: (2,6), (6,2), (3,5), (5,3), (4,4)
ØWhen
one
loop
is
contained
enJrely
within
another
we
say
that
they
are
nested
loops.
Ø The
larger
loop
is
called
the
outer
loop
Ø The
one
lying
within
it
is
called
the
inner
loop
ØIt
is
o[en
difficult
to
follow
the
logical
sequence
of
steps
when
nested
loops
are
implemented.
ØIt
is
very
important
to
be
able
to
walk
through
(desk
check)
the
pseudocode
with
paper
and
pencil,
carefully
wriJng
down
the
values
of
each
variable
at
each
step.
Games:
1
1
2
2
2
3 3
Workout
#3
1 3 3
Follow
1
1
3
3
4
4 Let’s do this some more!
4
Along…
1 4 4
2 1 2 2
2 1 4 4
2 2 4
2 2 6 6
2 3 6
2 3 8 8
2 3 8 Who do we appreciate?
2 4 8
3 4 8