Loop - CIS 1068 Program Design and Abstraction - PowerPoint PPT Presentation

1 / 79
About This Presentation
Title:

Loop - CIS 1068 Program Design and Abstraction

Description:

Title: PowerPoint Presentation Author: PC User Last modified by: zhen-Air Created Date: 3/11/2001 5:06:34 PM Document presentation format: On-screen Show (4:3) – PowerPoint PPT presentation

Number of Views:136
Avg rating:3.0/5.0
Slides: 80
Provided by: PCUs81
Learn more at: https://cis.temple.edu
Category:

less

Transcript and Presenter's Notes

Title: Loop - CIS 1068 Program Design and Abstraction


1
Loop - CIS 1068 Program Design and Abstraction
Zhen Jiang CIS Dept. Temple University SERC 347,
Main Campus Email zhen.jiang_at_temple.edu
2
Table of Contents
  • Taste of Loop
  • While Loop
  • Do While Loop
  • For Loop
  • Variations
  • Controlling Number of Loop Iterations
  • Loop Development
  • Mapping Iterations to Counter Values
  • Controlling Event of Loop Iterations
  • Random number generator
  • Fencepost problem (an interesting scenario)
  • Summary of Learning Materials

3
Taste of Loop
  • Price is right.
  • Sample execution (click on this link to try)
  • Before you get the price right, the program will
    REPEAT

4
while loop
  • while loop A control structure that repeatedly
    performs a test and executes a group of
    statements if the test evaluates to true.
  • while loop, general syntax
  • ltinitializationgt
  • while (lttestgt)
  • ltbody, consisting of statement(s)gt
  • Example
  • int number 1
  • while (number lt 200)
  • System.out.print(number " ")
  • number 2
  • Output
  • 1 2 4 8 16 32 64 128

5
  • The ltinitializationgt prepares the variable
    declarations and their values that are used in
    the test, update, and body of the loop.
  • The lttestgt checks whether the repetition of the
    loop body can stop.
  • The statement or group of statements to be
    repeated is called the ltbodygt of the loop.
  • Each repetition of the loop body is called an
    ltiterationgt of the loop.

Not clear?
6
  • ltinitializationgt
  • while (lttestgt)
  • ltbodygt

7
  • Finds and prints a number's first factor other
    than 1
  • Scanner console new Scanner(System.in)
  • System.out.print("Type a number ")
  • int number console.nextInt()
  • int factor 2
  • while (number factor ! 0)
  • factor
  • System.out.println("First factor " factor)
  • Sample run
  • Type a number 91
  • First factor 7

8
  • Example, WhileDemo.java, P202

9
Variant 1 do/while
  • do/while loop A control structure that executes
    statements repeatedly while a condition is true,
    testing the condition at the end of each
    repetition.
  • do/while loop, general syntax
  • ltinitializationgt
  • do
  • ltstatement(s)gt
  • while (lttestgt)
  • Example
  • // roll until we get a number other than 3
  • Random rand new Random()
  • int die
  • do
  • die rand.nextInt()
  • while (die 3)

10
  • How does this differ from the while loop?
  • The controlled ltstatement(s)gt will always execute
    the first time, regardless of whether the lttestgt
    is true or false.

11
  • Example, DoWhileDemo.java, P206

12
Variant 2 for
  • for loop A block of Java code that executes a
    group of statements repeatedly until a given test
    fails.
  • General syntax
  • for (ltinitializationgt lttestgt ltupdategt)
  • ltstatementgt
  • ltstatementgt
  • ...
  • ltstatementgt
  • Example
  • for (int i 1 i lt 30 i)
  • System.out.println("I will not throw...")

13
for (ltinitgt lttestgt ltupdategt) ltbodygt
14
  • Example, ForDemo.java, P219

15
  • Summary

Body first, and then event change/update
16
(No Transcript)
17
(No Transcript)
18
For loop?
19
  • Initialization, test, and body, and execution
    results of loop
  • Code
  • for (int i 1 i lt 4 i)
  • System.out.println(i " squared is " (i
    i))
  • Output
  • 1 squared is 1
  • 2 squared is 4
  • 3 squared is 9
  • 4 squared is 16

1st iteration? 2nd iteration? 3rd iteration?
20
Variations
  • The initial and final values for the loop
    counter/event variable can be arbitrary
    expressions
  • Example
  • for (int i -3 i lt 2 i)
  • System.out.println(i)
  • Output
  • -3
  • -2
  • -1
  • 0
  • 1
  • 2
  • Example
  • for (int i 1 3 4 i lt 5248 100 i)
  • System.out.println(i " squared is " (i
    i))

21
  • The update can be a -- (or any other operator).
  • Caution This requires changing the test from lt
    to gt .
  • System.out.println("T-minus")
  • for (int i 3 i gt 1 i--)
  • System.out.println(i)
  • System.out.println("Blastoff!")
  • Output
  • T-minus
  • 3
  • 2
  • 1
  • Blastoff!

22
  • What if we wanted the output to be the following?
  • T-minus 3 2 1 Blastoff!
  • System.out.print prints the given output without
    moving to the next line.
  • System.out.print("T-minus ")
  • for (int i 3 i gt 1 i--)
  • System.out.print(i " ")
  • System.out.println("Blastoff!")

23
  • When controlling a single statement, the
    braces are optional.
  • for (int i 1 i lt 6 i)?
  • System.out.println(i " squared is " (i
    i))
  • This can lead to errors if a line is not properly
    indented.
  • for (int i 1 i lt 3 i)?
  • System.out.println("This is printed 3
    times")
  • System.out.println("So is this... or is
    it?")
  • Output
  • This is printed 3 times
  • This is printed 3 times
  • This is printed 3 times
  • So is this... or is it?
  • Moral Always use curly braces and always use
    proper indentation.

24
  • Extra semicolon in a loop (P218).
  • int i
  • for (i 1 i lt 6 i)?
  • System.out.println(i " squared is " (i
    i))
  • Output
  • 7 squared is 49
  • Comman in a loop (P220).
  • int i, sum
  • for (i 1, sum 0 i lt 10 i)?
  • sum sum i i
  • System.out.println("Result is " sum)
  • Output
  • 385

int sum for (int i0, sum
25
  • Invalidation Loops that never execute.
  • for (int i 10 i lt 5 i)
  • System.out.println("How many times do I
    print?")
  • ERROR Loop tests that never fail.
  • A loop that never terminates is called an
    infinite loop.
  • for (int i 10 i gt 1 i)
  • System.out.println("Runaway Java
    program!!!")

26
  • Loops that go on forever
  • while (true)
  • ltstatement(s)gt
  • If it goes on forever, how do you stop?

27
  • break statement Immediately exits a loop (for,
    while, do/while).
  • Example
  • while (true)
  • ltstatement(s)gt
  • if (lttestgt)
  • break
  • ltstatement(s)gt
  • Why is the break statement in an if statement?

28
  • Sentinel loop using break
  • Scanner console new Scanner(System.in)
  • int sum 0
  • while (true)
  • System.out.print("Enter a number (-1 to
    quit) ")
  • int inputNumber console.nextInt()
  • if (inputNumber -1) // don't add -1 to
    sum
  • break
  • sum inputNumber // inputNumber ! -1
    here
  • System.out.println("The total was " sum)

29
  • Special case If a variable is declared in the
    ltinitializationgt part of a for loop, its scope is
    the for loop.
  • public static void main(String args)
  • int x 3
  • int i
  • for (i 1 i lt 10 i)
  • System.out.println(x)
  • // i no longer exists here
  • // x ceases to exist here

x's scope
is scope
30
  • ERROR Using a variable outside of its scope.
  • public static void main(String args)
  • for (int i 1 i lt 10 i)
  • int y 5
  • System.out.println(y)
  • System.out.println(i) // illegal
  • System.out.println(y) // illegal

31
  • COMMON ERROR Using the wrong loop counter
    variable.
  • But barely possible when you develop code with
    our process.
  • What is the output of the following piece of
    code?
  • for (int i 1 i lt 10 i)
  • for (int j 1 i lt 5 j)
  • System.out.print(j)
  • System.out.println()
  • What is the output of the following piece of
    code?
  • for (int i 1 i lt 10 i)
  • for (int j 1 j lt 5 i)
  • System.out.print(j)
  • System.out.println()

32
  • Exercises
  • http//www.cis.temple.edu/jiang/1068LoopExecution
    .pdf

33
Loop Development
 population   TV purchase  1248... 1234...
99
  • http//www.cis.temple.edu/jiang/LoopDevelopment.h
    tm

34
(No Transcript)
35
Controlling Number of Loop Iterations
  • If the number of iterations is known before the
    loop starts, the loop is called a
    count-controlled loop.
  • Counter 0, counter, counter ltnumber
  • Counter 1, counter, counter ltnumber
  • Use for loop for an easy development.

36
(No Transcript)
37
(No Transcript)
38
Mapping iterations to counter values
  • Suppose that we have the following loop
  • for (int count 0 count lt 49 count)
  • ...
  • What statement could we write in the body of the
    loop that would make the loop print the following
    output?
  • 0 2 4 6 8
  • Answer
  • for (int count 0 count lt 49 count)
  • System.out.print(2 count " ")

39
  • Now consider another loop of the same style
  • for (int count 0 count lt 49 count)
  • ...
  • What statement could we write in the body of the
    loop that would make the loop print the following
    output?
  • 3 5 7 9 11
  • Answer
  • for (int count 0 count lt 49 count)
  • System.out.print(2 count 3 " ")

40
  • What statement could we write in the body of the
    loop that would make the loop print the following
    output?
  • 2 7 12 17 22
  • To find the pattern, it can help to make a table.
  • Each time count goes up by 1, the number should
    go up by 5.
  • But count 5 is too big by 3, so we must
    subtract 3.

number to print
count 5
count 5 - 3
count
2
5
2
1
7
10
7
2
12
15
12
3
17
20
17
4
22
25
22
5
41
(No Transcript)
42
  • Caution This is algebra, not assignment!
  • Recall slope-intercept form (y mx b)?
  • Slope is defined as rise over run (i.e. rise /
    run). Since the run is always 1 (we increment
    along x by 1), we just need to look at the
    rise. The rise is the difference between the y
    values. Thus, the slope (m) is the difference
    between y values in this case, it is 5.
  • To compute the y-intercept (b), plug in the value
    of y at x 1 and solve for b. In this case, y
    2.
  • y m x b
  • 2 5 1 b
  • Then b -3
  • So the equation is
  • y m x b
  • y 5 x 3
  • y 5 count - 3

43
  • Algebraically, if we always take the value of y
    at
  • x 1, then we can solve for b as follows
  • y m x b
  • y1 m 1 b
  • y1 m b
  • b y1 m
  • In other words, to get the y-intercept, just
    subtract the slope from the first y value (b 2
    5 -3)?
  • This gets us the equation
  • y m x b
  • y 5 x 3
  • y 5 count 3
  • (which is exactly the equation from the previous
    slides)?

44
  • What statement could we write in the body of the
    loop that would make the loop print the following
    output?
  • 17 13 9 5 1
  • Let's create the loop table together.
  • Each time count goes up 1, the number should ...
  • But this multiple is off by a margin of ...

45
  • Coding (different from execution check)
  • nkeyboard.nextInt() // try 6!
  • for (int i 1 i lt n i)
  • System.out.print("")
  • System.out.println()
  • Output

What is the body? Counter-controlled loop?
46
  • More complicate case
  • nkeyboard.nextInt() // try 6!
  • for (int i 1 i lt n i)
  • for (int j 1 j lt n j)
  • System.out.print("")
  • System.out.println()
  • Output

What is the body? Counter-controlled loop?
47
  • Code
  • nkeyboard.nextInt() // try 5!
  • for (int i 1 i lt n i)
  • for (int j 1 j lt 10 j)
  • System.out.print(
  • (i j) " ")
  • System.out.println()
  • Output
  • 1 2 3 4 5 6 7 8 9 10
  • 2 4 6 8 10 12 14 16 18 20
  • 3 6 9 12 15 18 21 24 27 30
  • 4 8 12 16 20 24 28 32 36 40
  • 5 10 15 20 25 30 35 40 45 50

What is the body? Counter-controlled
loop? Initialization and body detail?
48
  • How to confirm the initialization correct?
  • On preparing the 1st iteration
  • How to ensure the detail of the body?
  • A consistent view of 1st, 2nd, 3rd iterations
  • Map of the counter value to the iteration
    expression

49
  • Code
  • nkeyboard.nextInt() // try 6!
  • for (i 1 iltn i) System.out.print()
  • System.out.println()
  • for (i 1 i lt n-2 i)
  • System.out.print()
  • for (int j 1 j lt n-2 j)
  • System.out.print( )
  • System.out.println()
  • for (i 1 iltn i) System.out.print()
  • System.out.println()
  • Output

What is the body? Counter controlled loop
50
  • Code
  • nkeyboard.nextInt() // try 6!
  • for (int i 1 i lt n i)
  • for (int j 1 j lt i j)
  • System.out.print("")
  • System.out.println()
  • Output

i each line!
51
  • Code
  • nkeyboard.nextInt() // try 6!
  • for (int i 1 i lt n i)
  • for (int j 1 j lt i j)
  • System.out.print(i)
  • System.out.println()
  • Output
  • 1
  • 22
  • 333
  • 4444
  • 55555
  • 666666

How many numbers each line? What are they?
52
  • Code
  • nkeyboard.nextInt() // try 5!
  • for (int i 1 i lt n i)
  • for (int j 1 j lt (n - i) j)
  • System.out.print(" ")
  • for (int k 1 k lt i k)
  • System.out.print(i)
  • System.out.println()
  • Output
  • 1
  • 22
  • 333
  • 4444
  • 55555

Space and numbers?
53
Controlling Event of Loop Iterations
  • Otherwise (unknown or unclear), the loop is
    called a event-controlled loop.
  • Use a while loop or a do-while loop for an easy
    checkpoint development.
  • Asking the user before each iteration if it is
    time to end the loop is called the
    ask-before-iterating technique.
  • Appropriate status update (or event initializing)
    for a sequence of iterations

54
(No Transcript)
55
  • Finds and prints a number's first factor other
    than 1
  • int n keyboard.nextInt() // try 91
  • int f 2
  • while (n f ! 0)
  • f
  • System.out.println("First factor" f)
  • Sample run
  • First factor7

Body exploring the factor. When/what to stop
the loop? n f 0 divisible! The range of
f? Initialization of f? The change of f?
56
  • Write a program that will repeatedly prompt the
    user to type a number until the user types a
    non-negative number, then square it.
  • Example log
  • Type a non-negative integer -5
  • Invalid number, try again -1
  • Invalid number, try again -235
  • Invalid number, try again -87
  • Invalid number, try again 11
  • 11 squared is 121

57
Body trying different value of n. When/what to
stop the loop? ngt 0 non-negative! The range of
n? -gt any (since nlt0) Initialization of n? The
change of n?
  • System.out.print("Type a non-negative integer
    ")
  • int n keyboard.nextInt()
  • while (n lt 0)
  • System.out.print("Invalid number, try again
    ")
  • n keyboard.nextInt()
  • int square n n
  • System.out.println(n " squared is " square)
  • Notice that the number variable had to be
    declared outside the while loop in order to
    remain in scope.

58
  • Write a class named DigitSum that reads an
    integer from the user and prints the sum of the
    digits of that number. You may assume that the
    number is non-negative.
  • Example
  • Enter a nonnegative number 29107
  • prints out 19 (i.e.,29107 )
  • Hint Use the operator to extract the last
    digit of a number. If we do this repeatedly,
    when should we stop?

59
Body adding the last digit and extracting that
from the original number (for next
round) When/what to stop? All digits are
counted! n lt 0 no more need to count! The
change of n? -gt make the extraction
valid Initialization?
  • import java.util.Scanner
  • public class DigitSum
  • public static void main(String args)
  • Scanner keyboard new Scanner(System.in)
  • int n keyboard.nextInt()
  • int sum 0
  • while (n gt 0)
  • sum n 10 // add last digit to sum
  • n n / 10 // remove last digit
  • System.out.println(sum sum)

60
Body try all possible numbers k, count k (sum)
only when n is divisible by k. When/what to stop?
Kgtn (trial from 1 is over) The range of k? -gt 1
to n Change? k Initialization?
  • Write a program named CountFactors that reads in
    an integer and displays its number of factors.
  • For example, if the user enters 60, CountFactors
    displays 12 because 1, 2, 3, 4, 5, 6, 10, 12, 15,
    20, 30, and 60 are all factors of 60.

Scanner keyboard new Scanner(System.in)
int n keyboard.nextInt() int sum 0, k
? while ( )
System.out.println(sum sum)
61
  • Scanner keyboard new Scanner(System.in)int n
    keyboard.nextInt()int k 1int sum
    0while (kltn) if(nk0) sum
    kSystem.out.print("sum " sum)

62
  • Exercises (Wednesday lab)

 population   TV purchase  1248... 1234...
99
63
(No Transcript)
64
(No Transcript)
65
  • Complete a Loop program
  • http//www.cis.temple.edu/jiang/1068LoopComplete.
    pdf

66
Random Number Generator
  • Objects of the Random class generate
    pseudo-random numbers.
  • Class Random is found in the java.util package.
  • import java.util.
  • The methods of a Random object

67
  • Random rand new Random()
  • int randomNum rand.nextInt(10)
  • // randomNum has a random value between 0 and 9
  • What if we wanted a number from 1 to 10?
  • int randomNum rand.nextInt(10) 1
  • What if we wanted a number from min to max (i.e.
    an arbitrary range)?
  • int randomNum rand.nextInt(ltsize of the rangegt)
    ltmingt
  • where ltsize of the rangegt equals (ltmaxgt - ltmingt
    1)?

68
  • Given the following declaration, how would you
    get
  • A random number between 0 and 100 inclusive?
  • A random number between 1 and 100 inclusive?
  • A random number between 4 and 17 inclusive?

69
  • Given the following declaration, how would you
    get
  • A random number between 0 and 100 inclusive?
  • int random1 rand.nextInt(101)
  • A random number between 1 and 100 inclusive?
  • int random1 rand.nextInt(100) 1
  • A random number between 4 and 17 inclusive?
  • int random1 rand.nextInt(14) 4

70
  • Write a program that simulates the rolling of two
    six-sided dice until their combined result comes
    up as 7.
  • Sample run
  • Roll 2 4 6
  • Roll 3 5 8
  • Roll 5 6 11
  • Roll 1 1 2
  • Roll 4 3 7
  • You won after 5 tries!

71
Body try all possible numbers When/what to
stop? Sum 7 The range of sum? -gt any (since
!7) Change? Depends on roll1 and
roll2 Initialization? Any, if !7, e.g., 0
  • import java.util.
  • public class Roll
  • public static void main(String args)
  • Random rand new Random()
  • int sum 0
  • int tries 0
  • while (sum ! 7)
  • int roll1 rand.nextInt(6) 1
  • int roll2 rand.nextInt(6) 1
  • sum roll1 roll2
  • System.out.println("Roll " roll1
    " " roll2 " " sum)
  • tries
  • System.out.println("You won after "
    tries " tries!")

72
Fencepost Problem
  • Fencepost Problem Write a class named
    PrintNumbers that reads in an integer called max
    and prints each number from 1 to max, separated
    by commas.
  • Example
  • java PrintNumbers
  • Please enter a maximum integer 5
  • should print
  • 1, 2, 3, 4, 5

73
  • We want to print n numbers but need only n - 1
    commas.
  • Similar to the task of building a fence
  • If we repeatedly place a post and wire, the last
    post has an extra dangling wire.
  • A flawed algorithm
  • for (length of fence)
  • plant a post.
  • attach some wire.

74
  • import java.util.Scanner
  • public class PrintNumbers
  • public static void main(String args)
  • Scanner keyboard new Scanner(System.in)
  • int max keyboard.nextInt()
  • for (int i 1 i lt max i)
  • System.out.print(i ", ")
  • System.out.println() // to end the line
  • Output when user enters 5
  • 1, 2, 3, 4, 5, // notice extra comma at end!

unnecessary
75
  • import java.util.Scanner
  • public class PrintNumbers
  • public static void main(String args)
  • Scanner keyboard new Scanner(System.in)
  • int max keyboard.nextInt()
  • for (int i 1 i lt max i)
  • System.out.print(", " i)
  • System.out.println() // to end the line
  • Output when user enters 5
  • , 1, 2, 3, 4, 5 // comma at beginning

unnecessary
76
  • The solution is to add an extra statement outside
    the loop that places the initial "post."
  • This is called a fencepost loop.
  • The revised algorithm
  • plant a post.
  • for (length of fence - 1)
  • attach some wire.
  • plant a post.

77
  • import java.util.Scanner
  • public class PrintNumbers
  • public static void main(String args)
  • Scanner keyboard new Scanner(System.in)
  • int max keyboard.nextInt()
  • System.out.print(1)
  • for (int i 2 i lt max i)
  • System.out.print(", " i)
  • System.out.println() // to end the line
  • Output when user enters 5
  • 1, 2, 3, 4, 5 // no extra comma!

78
Summary
  • WhileDemo.java, p202
  • DoWhileDemo.java, p206
  • ForDemo.java, p219
  • Exercises, slides 32, 45-52, 55-65, 70-71, 77

79
  • Test (controlling boolean expression, P201), body
    (P200), iteration (P200), and initialization
    (P228)
  • While (P201-204), do-while (P204-9), and for loop
    (P217-221)
  • Counter-controlled (P229) and event controlled
    loop
  • Mapping iterations to counter values
  • Trace and development template
  • Random number generator
  • The omission of and its side effect (P218)
  • Extra semicolon (P222) and comma (P224)
  • Invalidation and infinite loop (P213)
  • The use of break and its function (P236-7)
  • Scope of loop variable (P223)
  • Fencepost problem and its solution
Write a Comment
User Comments (0)
About PowerShow.com