CS141: Topics for Week 6: Sept 28, 30, Oct 2, 2015
Computer Science Headlines
ACM Tech News
Lab 5: Loops and Cards
Remember to review questions starting on p. 342.
while-loop (a pretest loop)
for-loop (a pretest loop)
unwinding and hand tracing
do-while-loop (a posttest loop)
Control variable, initialization, condition, update; loop body
counter, running total
running totals, accumulator
Monte Carlo Method
- Why do we have loop structures?
Repetition - print the numbers from 1 to 5. What about 10 to 1000?
Repetition more generally - print the numbers starting at n1 and ending at n2.
- Components of any loop:
- Loop variable - the variable that controls the looping
- Loop variable initialization - the starting value of the loop variable.
- Loop condition - this must be true for loop to continue
- Loop variable update - how does loop variable change after each loop
- Loop body - sequence of statements that are executed in the loop
- Types of loops:
- while-loops - used when the number of repetitions can't be predicted ahead of time (indefinite)
- for-loops - when you know precisely how many times you will loop (definite). Loop
variable only defined within loop.
- do-while-loops - checks condition at end; always executes the body at least once
- Figuring out what is going on - Hand tracing, unraveling the loop
- Common Errors: infinite loops, off-by-one
- Sentinel values - the user controls when to stop
- Checking for correct user input and break statements
- Common applications: Basic Looping Problems (pdf)
- Book examples: computing sums, averages, all matches, first match, max values, min values, comparing adjacent values
- Nested loops. See Nested Loop Problems (pdf)
- Random numbers and games- rolling a die, picking a card.
- Monte Carlo method
In Class Practice Activities
- Use a loop to print out the lyrics for 99 Bottles of Beer on the Wall.
- How does one represent a card?
- What is the UML Diagram for the BlackJack Game?
- Do all of these!! Basic Looping Problems (pdf)
- Once we get to nested loops, do all of these!! Nested Loop Problems (pdf)
- By the end of the chapter, you should be able to do all of these practice problems without blinking an eye! They are the
kind of coding questions you might see on an exam.
- BlackJack Preliminaries: