Looping Constructs 5'5 5'8 - PowerPoint PPT Presentation

1 / 16
About This Presentation
Title:

Looping Constructs 5'5 5'8

Description:

A Little History: Loops = IF GOTO. 050 PRINT 'Give me two positive numbers to add: ... GOTO 400. PRINT X Y. 400 PRINT 'Another addition?' 500 READ ANSWER ... – PowerPoint PPT presentation

Number of Views:48
Avg rating:3.0/5.0
Slides: 17
Provided by: Steve57
Category:

less

Transcript and Presenter's Notes

Title: Looping Constructs 5'5 5'8


1
Looping Constructs (5.5 5.8)
  • Conditionals allow us to build computations that
    depend on input values
  • for example, our calculator application that
    prompts for a number and an operation the does a
    calculation
  • But we can still only execute that calculation
    once
  • what if we wanted the option of doing more than
    one calculation
  • Loops let the number of calculations depend on
    unknown (input) values as well
  • do this 100 times (where 100 is an input)
  • do this until there is no more input
  • do this until the user (or other input) tells you
    to stop
  • do this while there is still space in the table
    to hold the result
  • do this until I have at least 5 successful runs
  • Sometimes you use a loop even if the value is
    known, as it saves writing code
  • print the first 10000 integers, one per line
  • The general form is
  • do this calculation repeatedly while some value
    is true
  • do this calculation repeatedly until some value
    is true
  • (do this calculation while some value is false)
  • do this calculation this number of times

2
Why the term "Loop"
BEGIN
read max
count 0
true
count gt max?
END
false
read num
true
num lt 0 ?
false
print num num
count count 1
3
A Little History Loops IF GOTO
  • 050 PRINT "Give me two positive numbers to add "
  • 100 READ X
  • READ Y
  • IF (X gt 0 Y gt 0) GOTO 300
  • PRINT "Invalid numbers, try again."
  • GOTO 400
  • PRINT X Y
  • 400 PRINT "Another addition?"
  • 500 READ ANSWER
  • 600 IF (ANSWER "Y") GOTO 050

MORE TRUE WHILE (MORE) PRINT "Give me
two positive numbers to add " READ X
READ Y IF (X lt 0 Y lt 0) PRINT
"Invalid numbers, try again." ELSE
PRINT X Y PRINT "Another
addition?" READ ANSWER MORE (ANSWER
"Y")
4
The while statement
while (true) System.out.println(Stop me!)
while (boolean-expression) statements
while (false) System.out.println(Start
me!)
boolean continu true while (continu) int
input getUserInput() doCalculation(input)
continu askToContinue()
int counter 1 while (counter lt 100)
doSomethingToElement(counter) counter
int counter 0 while (counter lt 100)
doSomethingToElement(counter) counter
while (fileHasRecords()) String line
getLineFromFile() processLine(line)
int trials 0, successes 0 while ((trials lt
1000) (successes lt 10)) if
(doTrialSuccessfully()) successes
trials
5
Basic Types of Loops
  • User input loop
  • user types in string print it in upper case
  • user types in two numbers on a line report the
    sum
  • user types in sequence of integers report the
    sum
  • how is the length of the list communicated?
  • calculator example
  • Input validation loop
  • prompt for some sort of input keep trying until
    the input is valid
  • Loop over a collection of objects
  • all lines in a file
  • file contains a sequence of integers
  • report the sum
  • report the maximum
  • report whether all the integers are positive
  • report whether the sequence is in ascending order
  • all characters in a string
  • how many whitespace characters are there?
  • is every character a digit?
  • Loop until some condition holds

6
Sentinels versus Loop breaks
  • In every loop there is some point at which you
    calculate the termination condition
  • in a user input loop you ask the user (and get
    y or n or an empty line)
  • in an input loop reading integers, you use
    negative number as termination condition
  • in a file loop, you ask whether the file has more
    lines
  • in a loop over a sequence, you ask whether you
    are at the end of the sequence
  • in other loops, you see whether you have produced
    enough results
  • It is a common programming idiom to assign this
    termination condition (a boolean value) to a
    variable
  • the variable is called a sentinel variable
  • the termination clause in the while loop refers
    (only) to this variable

7
Sentinels in Action
boolean fileHasInput aScanner.hasNext() while
(fileHasInput) String nextLine
aScanner.nextLine() processLine(nextLine)
fileHasInput aScanner.hasNext()
Sentinal is initialized outside of loop Sentinal
is tested in loop test Sentinal is updated in
loop body
boolean continue true while (continue)
String nextLine aScanner.nextLine()
processLine(nextLine) System.out.print(Quit?
) String response aScanner.next() continue
!response.equals(yes)
8
Implicit Sentinals
boolean moreLines aScanner.hasNextLine() while
(moreLines) String nextLine
aScanner.nextLine() processLine(nextLine)
moreLines aScanner.hasNextLine()
Are they equivalent? Which is better code?
while (aScanner.hasNext()) String nextLine
aScanner.nextLine() processLine(nextLine)
9
When Sentinels Get Awkward (the case for break)
boolean continue true while (continue)
System.out.print(Another? ) String response
aScanner.next() if (response.equals(yes))
continue true processCommand() else
continue false System.out.println("D
one")
Are they equivalent? Which is better code?
while (true) System.out.print(Another? ) if
((aScanner.next()).equals(yes)) break
processCommand() System.out.println("Done")
10
The for loop
  • The for loop adds no power to the language (only
    convenience, and a throwback to the C language,
    which in turn was a throwback to the FORTRAN
    language, for which FOR was the main (only?)
    looping structure)
  • Generally only used for the counting loops

for (int i 0 i lt 100 i )
System.out.println(i)
int i 0 while (i lt 100) System.out.println(
i) i
boolean abExit false int sum 0 for (int i
0 i lt 5 i ) if (!sc.hasNextInt())
abExit true break sum
sc.nextInt() if (abExit)
System.out.println("Bad input stream") else
System.out.println(sum)
11
For loop and other sequences
String s "HEllO wOrLD!" int upperCaseCount
0 for (int i 0 i lt s.length()) if
(Character.isUpperCase(s.charAt(i )))
upperCaseCount 1 System.out.println(
upperCaseCount)
12
The for loop and multiple clauses
public static void main(String args)
String aString "Hello world" String bString
"dlrow olleH" System.out.println(isMirror(aS
tring, bString)) public static boolean
isMirror(String s1, String s2) boolean
mirror if (s1.length() ! s2.length())
mirror false else mirror
true for (int i0, j s2.length() - 1 i lt
s1.length() i, j-- ) if
(s1.charAt(i) ! s2.charAt(j))
mirror false break
return mirror
13
Nested Loops
  • Often times when you have two variables "looping"
    at once, you really want a nested loop (a loop
    within a loop)
  • Print the line in a file that has the maximum
    number of upper-case characters
  • loop over all lines, and for each line loop over
    characters in that line
  • For each character in a string, count the
    instances of that character in another string
  • loop over all characters in the first string
    for each character loop over the other string
  • For each number between 1 and 100, compute the
    factorial
  • loop over 1 to 100, and for each number loop over
    all smaller numbers
  • (Do each of these examples.)

14
Collections and the Iterator Interface
  • Terminology
  • Collection is an abstract term to refer to any
    collection of objects (a set, a sequence)
  • a String is a collection of characters
  • a file is a collection of Strings (one String per
    line)
  • a String or File can also be viewed as a
    collection of tokens
  • Remember the Scanner class and the concept of
    tokens

T
h
i
s
s
t
r
i
n
g
\n
\n

h
a
s


5

\t

t
o
k
e
n
s
.
.
.
\n
(The String also has three lines. The String
also has 33 characters.)
15
Accessing Collections Positional versus
Sequential
  • We access the String collection positionally (by
    index). That is, we can ask for the 3rd element
    in the collection (3rd character in the String)
    without having to go through the 1st or 2nd
    character to get there
  • Not all collections allow positional access. For
    example, a File is a collection of Strings, but
    you can't look at (read) the 3rd line of the file
    until you have first read the first two.
  • This is called sequential or iterator access of
    the collection. You get all of the elements
    through two methods
  • do you have a next element?
  • give me the next element
  • Many classes in Java agree to give these two
    (actually three) methods common names
  • boolean hasNext()
  • Object next() // This is why we
    have to case sc.next()
  • void remove()

16
The Iterator Interface
  • Any class that allows this kind of access (that
    implements these methods) is said to implement
    the Iterator interface
  • this might apply to a collection of Strings or of
    Numbers or of Employees or of Students so the
    iterator convention just returns an Object
  • String does not implement this interface
  • that is, there is no hasNext() or next() methods
    implemented as part of the String class
  • but it is extremely easy to implement it
  • Scanner does implement this interface and this is
    how the idiom looks

Scanner s new Scanner("This string\n\nhas
five(5) \ttokens...\n") while (s.hasNext())
String nextToken (String)s.next()
System.out.println(nextToken)
Write a Comment
User Comments (0)
About PowerShow.com