Go Over Test - PowerPoint PPT Presentation

1 / 50
About This Presentation
Title:

Go Over Test

Description:

How and where should we compute the average? 24. Finding a Max and Min ... do-while loop) that helps to launch the space shuttle--print out. 10. 9. 8. 1. Blast Off! ... – PowerPoint PPT presentation

Number of Views:18
Avg rating:3.0/5.0
Slides: 51
Provided by: davidh67
Category:
Tags: over | test

less

Transcript and Presenter's Notes

Title: Go Over Test


1
Go Over Test 1
  • Grade Breakdown (Fall 2005)
  • A's 6
  • B's 2
  • C's 3
  • How to Study for CSc-037
  • Visit the instructor's office for help
  • Work on HW Early (as opposed to starting it the
    night before it is due)
  • Read Text Before After Class
  • Make sure you understand what's happening in Lab
  • Play with Sample Programs in Course Folder
  • Work on Exercises in Textbook
  • Try Sample Tests without looking at answers
  • (not just the night before the test)

2
Week 04 - b
  • The while Loop The do-while LoopReading Input
    in a Loop
  • The for Loop

3
Sample Programs Referenced(code located in
course folder)
  • BubbleGum
  • java loops.WhileLab
  • (AnimatedIllustrations)
  • Count Digits
  • InfiniteLoop
  • Display Word
  • Target
  • BouncingBall
  • 23Matches Game

4
Introduction to Repetition
  • Control structures regulate flow of execution in
    a program or method
  • Individual instructions combined into a single
    logical unit with
  • One entry point
  • One exit point
  • 3 Types of Control Structures
  • Sequence
  • Selection
  • Repetition

5
Repetition
  • Two types of Repetition
  • Condition Controlled
  • repeat something while a condition remains true
  • e.g. while not at your destination, keep driving
  • Counter Controlled
  • repeat something a certain number of times
  • e.g. drive 100 miles (or drive a mile 100 times!)

6
Bubble Gum ExampleBlueJ
  • Make an applet that shows a bubble popping
  • The applet should make a bubble and ask it to
    pop
  • The bubble should grow larger and larger until it
    fills the applet window and pops
  • Demonstrate the applet
  • The classes
  • BubbleApplet - applet with paint
  • Bubble
  • has a maximum radius and a Graphics object
  • has a pop method
  • draws larger and larger circles

7
Popping the Bubble
  • Algorithm for pop method
  • initialize the bubbles radius to 1
  • while the bubble fits in the window
  • draw the bubble in the center of the window
  • increase the bubbles radius
  • wait a short time
  • clear the window (to simulate popped bubble)
  • write the word POP in the center of the window
  • How do we implement the loop?

8
while Loop
  • Repeatedly executes body of the loop which can be
    a single or compound statement
  • A while loop will execute as long as its
    condition is true
  • An infinite loop will occur if the condition
    never becomes false

while (condition) statement
9
Review the Bubble Code
  • Applet
  • Bubble
  • Constructor
  • What does it receive as parameters?
  • What does it do?
  • Trace the execution of the pop method
  • What happens in the loop?
  • How does it end?
  • What would happen if we didnt add 1 to the
    radius inside the loop body?
  • What would happen if we started the radius at
    maxRadius?
  • Aside Take a look at the wait method in the
    Timer class
  • Note use of static. What kind of method is it?
    How is it called?

10
while Loop(Animated Illustrations)
  • java loops.WhileLab

11
Danger Semicolon Ahead
  • What would happen in the following code?
  • x 5
  • while (xgt0)
  • out.println(x)
  • x--

12
Stopping "Infinite" Loops
  • Click "Halt" in the Debugger Window
  • Click "Terminate" in the Debugger Window
  • OR ltCtrl/Alt/Deletegt
  • and run "Task Manager"

13
do-while Loop
  • Alternative to the while loop for conditional
    repetition
  • Test done at the bottom of the loop
  • Always executes the body of the loop at least
    once
  • while loop can be used to solve the same
    problems, but for some problems the do-while is
    easier to read

do statement while (condition)
14
A do-while ExampleBlueJ
  • Count the number of digits in a whole number
  • Idea keep dividing the number by ten (removing a
    digit) until the number reaches 0 and count the
    number of times you divide.
  • We want 0 to yield "1 digit"
  • Example number 251
  • divide by 10 ? 25 (count is 1)
  • divide by 10 ? 2 (count is 2)
  • divide by 10 ? 0 (count is 3)

15
Reading in a Loop
  • What if we want to do something with the input as
    we read it?
  • Example
  • read in a string
  • calculate the number of characters in the string
  • display the string and the number of characters
  • repeat until the user enters the string STOP
  • STOP is called the sentinel (signal)
  • We could be reading in numbers and stop when we
    get a negative value (if negative values were not
    legal input). -1 would be the sentinel

16
Sentinel-Controlled Loops 1 of 2
  • do forever
  • read input
  • if input is the sentinel value, exit the loop
  • process the input
  • Pro more natural sequence in loop body
  • Con exit in middle of loop
  • How do we loop forever? exit a loop in the
    middle?

17
Forever loops
  • What if the condition is always true?
  • Infinite loop
  • How can we make it be true always?
  • while (true)
  • How can we exit the loop?
  • break statement (as used in switch)

18
Sentinel-Controlled Loops 2 of 2
  • Code pattern using forever loop
  • while (true)
  • read input
  • if ( end-of-input ) break
  • process input
  • // end while loop

19
Error Handling
  • A forever loop is also useful for fool-proof
    input.
  • Pattern

Prompt for value while (true) Read
value if (value is valid) break
Display error message
This is good because control will only leave the
loop if/when the user enters a valid value.
20
Sentinel Example(Part of HW 4)
  • Want to read in a set of exam scores and
  • count the number of scores read
  • compute the sum (for average) of the scores
  • determine the highest and lowest scores
  • Algorithm
  • do forever
  • read a score
  • if SENTINNEL was read, exit loop
  • process the score

21
Problem Analysis
  • Read in a set of exam scores and evaluate them
  • count the number of Outstanding, etc.
  • compute the average of the scores
  • determine the highest and lowest scores

22
Counting in a Loop
  • How do we count the scores?
  • What is the process step?
  • What variable(s) will be required?
  • What should the scope of the variable(s) be?

23
Accumulating in a Loop
  • Our program should compute the average of the
    scores
  • Average is the sum divided by the count
  • How do we compute the sum?
  • Manually?
  • What is the process step?
  • What variable(s) will be required?
  • How and where should we compute the average?

24
Finding a Max and Min
  • Our program should determine the max and min
    scores
  • How can we do this? Ideas?
  • initialize min to Integer.MAX_VALUE
  • initialize max to Integer.MIN_VALUE
  • Modify the algorithm
  • New variables?
  • Walk through the algorithm to test it

25
HW 4
  • A. Grade Analysis
  • (Problem 4, page 268)
  • B. Fading into the Horizon
  • (Problem 12, page 269)

26
2 "Volunteers" To the Board
  • Write a while loop (2nd person write a do-while
    loop) that helps to launch the space
    shuttle--print out
  • 10
  • 9
  • 8
  • ...
  • 1
  • Blast Off!

27
Java BREAK
28
Additional Integer Operators
  • Increment
  • num
  • equivalent to ? num num 1
  • Decrement
  • num--
  • equivalent to ? num num - 1
  • Compound Operations
  • num 2
  • equivalent to ? num num 2
  • num - 2
  • equivalent to ? num num 2

29
Repetition
  • Two types of repetition
  • condition controlled
  • repeat something while a condition remains true
  • e.g. while not at your destination, keep driving
  • counter controlled
  • repeat something a certain number of times
  • e.g. drive 100 miles (or drive a mile 100 times!)
  • We now look at implementing counter-controlled
    loops in Java

30
Counter-Controlled Loops
  • Frequently we know how many times we want to
    repeat a task a priori.
  • Examples
  • A baseball game has 9 complete innings (ignore
    tie games).
  • 3 outs per inning
  • Display 5 circles in an applet
  • Process the characters in a String
  • (know the length)
  • A course usually has a fixed number of students ?
    fixed number of scores
  • Algorithm
  • For each student
  • Read a score
  • Process the score

31
Counter-Controlled Loops
  • The for loop is normally used to count through a
    range of values

for (int count first count lt last
count3) Statement
Such a loop will count from first to last,
executing Statement once for each value in the
range first..last.
32
for Loop Example
  • An example first
  • for (count 1 // 1. Initialization
  • count lt 5 // 2. Test
  • count) // 3. Update
    (Increment)
  • // statements to do // body of loop
  • 1. Initialize count to 1
  • 2. Evaluate count lt 5
  • true,
  • body is executed
  • increment count by 1
  • repeat
  • false, body is skipped

33
The for Loop
  • Syntax
  • for (initialization-statement // 1.
    Initialization
  • test-condition // 2. Test
  • update-statement) // 3. Update
  • statement-or-compound-statement // Body
  • How it works
  • 1. Perform initialization
  • 2. Evaluate condition
  • true,
  • body is executed
  • perform update statement
  • repeat
  • false, body is skipped

Could we do the same thing with a while loop ?
34
Count by tens
  • Write a for loop to count from 0 to 100 by 10s.

for (int count 0 count lt 100 count10)
System.out.println(count)
Modify the loop to count from 100 down to 0 by
10s.
for (int count 100 count gt 0 count-10)
System.out.println(count)
35
For Loop Examples
  • Experiment with Java code for the following
    examples
  • "for" Example 1 (should be able to do these
    easily)
  • Print the integers 1 through 5 - one at a time in
    order
  • Print the even integers 0 through 6
  • Print the integers 5 down to 1
  • "for" Example 2 (see BLUEJ)
  • Write a word down the page a character at a time
  • Example 3 (next slide)
  • Display a multi-circle target
  • (next slide)

36
BullsEye redux
  • Display a "Target" using a for loop
  • Review code
  • Experiment with the for loop
  • Try smaller number of circles
  • Try incrementing by 2

37
Compute N factorial
  • N! N (N-1) (N-2) 2
  • e.g. 4! 4 3 2 24
  • Algorithm
  • Initialize product to 1 (multiplicative identity)
  • Initialize multiplier to number (N)
  • Loop
  • Compute product product multiplier
  • Decrement multiplier by 1
  • End loop
  • Return product
  • What terminates the loop? What kind of loop?

38
factorial Function
  • public static long factorial (int num)
  • // long to allow big values
  • long product 1 // multiplicative identity
  • for (int m num m gt 2 m--)
  • product m
  • return product
  • // end of factorial method

39
"Perfect" Numbers
  • An positive integer is said to be perfect if it
    is equal to the sum of its factors
  • including 1
  • obviously excluding itself
  • Try a few integers such as 6, 17, 28, 59,

40
Code to Check for a"Perfect" Number
  • public static boolean isPerfect(int n)
  • int sum 0
  • for (int divisor1 divisorltn divisor)
  • if (n divisor 0)
  • sum divisor
  • return (sum n)
  • // end of isPerfect method

41
Bouncing Ball
  • Suppose that when a ball is dropped, it bounces
    from the pavement to a height one-half of its
    previous height.
  • We want to write a program that will simulate the
    behavior of the ball.
  • The program should count the number of bounces
    that it will take before the height is less than
    some minimal height.

42
Path of the Bouncing Ball
43
Follow the Bouncing Ball
Algorithm Initialize bounce count to 0 Prompt
for and read height Loop Replace height by
height / 2 Add 1 to bounce End loop
  • How/Where should repetition terminate?
  • What kind of loop should be used?
  • What if we were asking how high the ball would
    be after 10 bounces?

44
Code for Bouncing Ball
  • /
  • Calculate how many times a ball will bounce.
  • _at_author Dave Hannay
  • _at_version CSc-105 Demo
  • /
  • public class BouncingBall
  • final double MIN_HEIGHT 0.01 // somewhat
    arbitrary
  • public int bounce(double height)
  • int bounce 0
  • while (height gt MIN_HEIGHT)
  • height / 2.0
  • bounce
  • // end of while (height gt MIN_HEIGHT)
  • return bounce
  • // end of bounce method
  • // end of BouncingBall class

45
General Game Control(pseudocode)
  • boolean computerTurn false
  • Gameboard game new Gameboard()
  • do
  • if (computerTurn)
  • game.makeComputerMove()
  • else
  • game.getHumanMove()
  • computerTurn !computerTurn
  • while (!game.gameOver())

46
Game of 23 Matches
  • Start with 23 matches lying on a table.
  • On each turn, you may take 1, 2, or 3 matches.
  • You alternate moves with the computer, and the
    one who takes the last match loses.
  • Similar to "Old Maid"

47
Code for "23 Matches" Game
  • public class Matches23Client
  • public static void main(String args)
  • boolean computerTurn false
  • Matches23 matches new Matches23()
  • do
  • matches.display()
  • if (computerTurn)
  • matches.makeMove()
  • else
  • matches.getHumanMove()
  • computerTurn !computerTurn
  • while (!matches.gameOver()) // game over if
    no more matches
  • System.out.println()
  • if (computerTurn)
  • System.out.println("I win, you lose!")
  • else
  • System.out.println("Amazing as this may
    be, you beat me!")
  • // end of main method
  • // end of Matches23Client class

48
Matches23 Class
  • View class in BlueJ

49
To the Computers...
  • Try to beat the computer at "23 Matches"
  • Drag from course folder
  • (Matches Game on Palm Computer)

50
Java BREAK
Write a Comment
User Comments (0)
About PowerShow.com