COMP 14 Introduction to Programming - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

COMP 14 Introduction to Programming

Description:

COMP 14. Introduction to Programming. Jingyu Yan. February 14, 2005. Announcements ... look at previous mid-term, homework exercises, in-class exercises, words in bold ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 49
Provided by: michele9
Category:

less

Transcript and Presenter's Notes

Title: COMP 14 Introduction to Programming


1
COMP 14Introduction to Programming
  • Jingyu Yan
  • February 14, 2005

2
Announcements
  • Mid-Term Exam - March 9
  • covers Chapters 1-5
  • look at previous mid-term, homework exercises,
    in-class exercises, words in bold print in
    textbook
  • This Wednesday
  • Please bring your laptop

3
Loops
  • Allow us to repeat statements some number of
    times
  • Must use a loop control variable
  • controls how many times to loop
  • 4 Parts to Every Loop
  • initialization - set loop control variable before
    condition
  • condition - when to stop
  • update - change to the loop control variable
  • body - actions to repeat

4
Typical Uses of Loops
  • Repeat a section of code a specified number of
    times - counter-controlled
  • Repeat a section of code (reading input) until
    the a specific value is read - sentinel-controlled
  • Repeat a section of code (reading input) until a
    valid value is entered - input validation
  • Repeat a section of code (reading from a file)
    until the end of the file is reached -
    EOF-controlled
  • Repeat a section of code until a boolean variable
    becomes false - flag-controlled

5
Questions
  • What type of while loop should be used?
  • Read every line in a file until the number -99 is
    read.
  • Read every line in a file where the length of the
    file is unknown.
  • Make sure that the user enters a lowercase
    letter.
  • Print the even numbers between 0 and 50.

sentinel-controlled
EOF-controlled
input validation
counter-controlled
6
The while Loop
while (expression) statement
7
The while Loop
  • final int LIMIT 3
  • int count 0
  • while (count lt LIMIT)
  • System.out.println (count)
  • count
  • System.out.println (All done!)

boolean condition
Output 0 1 2 All done!
initialization
loop body
update
8
In-Class Exercise
  • Write a while loop that prints
  • 2
  • 4
  • 6
  • 8

int i 2 while (i lt 8) System.out.println
(i) i 2
int i 1 while (i lt 4) System.out.println
(i2) i
9
In-Class Exercise
  • Write a while loop that prints the odd numbers
    between 0-100.

int i 0 while (i lt 100) if ((i 2) 1)
System.out.println (i) i
int i 1 while (i lt 99) System.out.println
(i) i2
10
Question
  • What is the loop control variable in the
    following while loop?
  • int count 0, num
  • num Integer.parseInt(keyboard.readLine())
  • while (num lt 0)
  • System.out.println (num)
  • num Integer.parseInt(keyboard.readLine())
  • count

num
11
Today in COMP 14
  • The for loop
  • The do...while loop
  • break and continue
  • Nested loops
  • Textbook Reference Ch 5 (pgs. 229-247)

12
The for Loop
  • Specialized form of while loop
  • Simplifies the writing of counter-controlled
    loops
  • Basic Form

for (initialization condition update)
statement(s)
13
The for LoopExecution
  • initial statement executes
  • loop condition evaluated
  • If loop condition evaluates to true, execute for
    loop statement and execute update statement
  • Go back to step 2 and repeat until loop condition
    is false

14
The for LoopSyntax
for ( initialization condition update )
loop body
15
for vs. while
  • A for loop is functionally equivalent to the
    following while loop structure

initialization while ( condition ) loop
body update
16
The for LoopExample
Output 0 1 2 All done!
  • final int LIMIT 3
  • int count
  • for (count0 countltLIMIT count)
  • System.out.println (count)
  • System.out.println (All done!)

boolean condition
initialization
update
loop body
17
Comparing while and for
  • While Loop
  • final int LIMIT3
  • int i 0
  • while (i lt LIMIT)
  • System.out.println (i)
  • i
  • System.out.println
  • (All done!)

For Loop final int LIMIT3 int i for (i0
iltLIMIT i) System.out.println
(i) System.out.println ("All done!")
18
The for Loop
  • Like a while loop, the condition of a for
    statement is tested prior to executing the loop
    body
  • The body of a for loop will execute zero or more
    times
  • It is well suited for executing a loop a specific
    number of times that can be determined in advance
  • Anything you can do in a for loop, you can do in
    a while loop

19
The for Loop
  • Does not execute if initial condition is false
  • Update expression changes value of loop control
    variable, eventually making it false
  • If loop condition is always true, result is an
    infinite loop
  • for statement ending in semicolon is empty does
    not affect program

for (count0 countltLIMIT count)
20
Examples
Hello Hello Hello Hello Hello
for (i1 ilt5 i) System.out.println
("Hello") System.out.println ("")
for (i1 ilt5 i) System.out.println
("Hello") System.out.println ("")
Hello Hello Hello Hello Hello
for (i1 ilt5 i) System.out.println ("")

21
Multiples.java Example
  • Ask the user for a positive number
  • Ask the user for a limit
  • Print all of the multiples of the positive number
    up to limit
  • What happens if the user enters a negative number?

22
In-Class Exercisefor vs. while Loops
Output 0 3 6 9 12 15 18
  • final int MAX 20
  • int i
  • for (i 0 iltMAX i3)
  • System.out.println (i)
  • Predict the output
  • Translate this to a while loop.

final int MAX 20 int i 0 while (i lt MAX)
System.out.println (i) i 3
23
The dowhile Loop
  • Statements executed first, then expression
    evaluated
  • Statement(s) executed at least once then
    continued if expression is true
  • Basic Form

do statement(s) while (expression)
24
The do...while LoopSyntax
do loop body while ( condition )
The loop body is executed once initially, and
then the condition is evaluated
The loop body is executed repeatedly until the
condition becomes false
25
dowhile Loop(Post-test Loop)
do statement(s) while (expression)
26
The do...while Loop
  • Like a while loop, but its condition is at the
    end of the loop
  • Loop body always executes at least once
  • Must also be checked for termination (not an
    infinite loop)
  • Anything you can do with a do...while loop, you
    can do with a while loop

27
The do...while LoopExample
  • final int LIMIT 3
  • int count 0
  • do
  • System.out.println (count)
  • count
  • while (count lt LIMIT)
  • System.out.println (All done!)

Output 0 1 2 All done!
initialization
loop body
update
boolean condition
28
Comparing while and do...while
  • while Loop
  • final int LIMIT3
  • int count 0
  • while (count lt LIMIT)
  • System.out.println (count)
  • count
  • System.out.println
  • (All done!)
  • do...while Loop
  • final int LIMIT3
  • int count 0
  • do
  • System.out.println
  • (count)
  • count
  • while (count lt LIMIT)
  • System.out.println
  • ("All done!")

29
while vs. do...while
i 11 while (i lt 10) System.out.print (i
" ") i 5 System.out.println()
blank line
i 11 do System.out.print (i " ") i
5 while (i lt 10) System.out.println()
11
30
In-Class ExerciseThe do...while Loop
  • int x 0, y 0
  • do
  • System.out.println (xy)
  • if (y lt x)
  • y 2
  • x
  • while (x lt 5)
  • Predict the output of the loop
  • x y
  • 0 0
  • Output

2
1
4
2
3
4
5
0
0
4
6
16
31
break Statements
  • Used to exit early from a loop
  • Used to skip remainder of switch structure
  • Can be placed within if statement of a loop
  • If condition is met, loop exited immediately

32
break Example
int i for (i0 ilt5 i) System.out.print
("i ") if (i 2) break System.out.p
rintln (i)
i 0 i 1 i
33
continue Statements
  • Used in while, for, and do...while structures
  • When executed in a loop, the remaining statements
    in the loop are skipped proceeds with the next
    iteration of the loop
  • When executed in a while/dowhile structure,
    expression evaluated immediately after continue
    statement
  • In a for structure, the update statement is
    executed after the continue statement then the
    loop condition executes

34
continue Example
int i for (i0 ilt5 i) System.out.print
("i ") if (i 2) continue System.ou
t.println (i)
i 0 i 1 i i 3 i 4
int i0 while (ilt5) System.out.print ("i
") if (i 2) continue System.out.prin
tln (i) i
i 0 i 1 i i i ... (infinite loop)
35
Nested Control Structures
  • Provides new power, subtlety, and complexity
  • if, ifelse, and switch structures can be placed
    within while loops
  • for loops can be found within other for loops
  • each time through the outer loop, the inner loop
    goes through its full set of iterations

36
Nested Control Structures Example
  • for (int row 1 row lt 5 row)
  • for (int star 1 star lt row star)
  • System.out.print()
  • System.out.println()

Output
  • Can't use the variable row outside the outer for
    loop.
  • Can't use the variable star outside the inner
    for loop.

37
Flips.java Example
  • Flip a coin 5 times
  • choose a random number
  • Print the total number of heads and tails

38
Loop Features
39
Choosing a Loop Structure
  • while
  • you don't know how many times to execute the loop
    body
  • do...while
  • you don't know how many times to execute the loop
    body, but it's at least once
  • for
  • you know exactly how many times to execute the
    loop body

40
Loops
  • 4 parts of every loop
  • initialization
  • condition
  • loop body
  • update
  • Order
  • while and for
  • initialization
  • condition
  • loop body
  • update
  • do...while
  • initialization
  • loop body
  • update
  • condition

41
Program 3
  • Rock-Paper-Scissors-Spock-Lizard
  • variation on Rock-Paper-Scissors
  • Have the computer choose one of the 5 shapes.
  • Hint Math.random
  • Ask the user to choose one of the 5 shapes or 'q'
    to quit.
  • Decide who wins.
  • After the user quits, print out a tally of the
    user wins, losses, and ties.

42
Program 3
  • You must print the title of the game.
  • You must make sure the user knows what to enter
    to choose a particular shape.
  • Allow the user to enter invalid input and prompt
    them for valid input.
  • You do not have to use letters for selecting the
    shapes.
  • Start early!

43
Program 3Break Program into Smaller Steps
  • Print out welcome message, options, and
    directions to user
  • Write a loop that allows the user to enter a
    character and end the loop if the user enters 'q'
    (or 'Q')
  • Write code that will print out the shape (rock,
    paper, ...) based on what the user entered
  • Write code that will make the computer choose a
    shape
  • Write code that will print out what shape the
    computer chose

44
Program 3Break Program into Smaller Steps
  • Write code that decides if the computer or the
    user won
  • Write code that will keep up with the number of
    wins, losses, and ties for the user
  • Write code that will print out the number of
    wins, losses, and ties after the user chooses to
    quit

45
Math.random Example
  • Print a random number in -1, 0, 1.

double randomNum int sample012 //
Math.random() will return 0.0, 1.0) randomNum
Math.random() // sample012 will be 0, 1,
2 sample012 (int) (randomNum 3) //
print out -1, 0, 1 System.out.println(sample01
2 - 1)
System.out.println ((int) (Math.random() 3) -
1)
46
In-Class ExerciseRandom
  • Write a code fragment to choose a random number
    in 0, 1, 2, 3.
  • Print 'A' if the number chosen is 0, 'B' if the
    number is 1, 'C' if the number is 2, and 'D' if
    the number is 3.
  • Hint a switch statement would be appropriate here

sample (int) (Math.random() 4)
47
  • int sample
  • // sample will be 0, 1, 2, 3
  • sample (int) (Math.random() 4)
  • switch (sample)
  • case 0
  • System.out.println("A")
  • break
  • case 1
  • System.out.println("B")
  • break
  • case 2
  • System.out.println("C")
  • break
  • case 3
  • System.out.println("D")
  • break

48
Next Time in COMP 14
  • Programming Session
  • Please bring your laptop
Write a Comment
User Comments (0)
About PowerShow.com