cs121: computer programming i this week’s...

16
1 CS121/IS223 Week 3, Slide 1 CS121: Computer Programming I Loops in Java Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors (see the schedule posted on my webpage) YOU MUST TRY THE EXAMPLES AND EXERCISES CS121/IS223 Week 3, Slide 2 This week’s Agenda More control structures in Java • Loops: – while statements – do-while statements – for statements Infinite loops Nested loops Basically these 3 statements do the same thing - you can rewrite loops using different statements, but sometimes one type looks neater than the others CS121/IS223 Week 3, Slide 3 Controlling the Program Flow Recall – an imperative program is a sequence of commands Using conditional statements in a programming language: – you can control the order in which these commands are executed – you can also control whether or not these commands are actually executed There are other ways to control the program flow… CS121/IS223 Week 3, Slide 4 Control Structures - Recap Flow of control is the order in which program statements are executed Most programming languages have 2 kinds of statements to regulate flow of control: conditionals – branching/selection statements that choose one set of statements over one or more other sets loops – repeat a set of statements again & again until a stopping condition is reached They often rely on boolean expressions CS121/IS223 Week 3, Slide 5 Loops A group of repeated statements Loop body - group of statements to be repeated Each repetition of a loop is called an iteration Loop condition – mechanism for deciding when & how the repetition stops One thing – many times! CS121/IS223 Week 3, Slide 6 LOGO: http://el.media.mit.edu/logo-foundation/ Remember This? Forward 50 Right 90 Forward 50 Right 90 Forward 50 Forward 50 Right 90 Right 90

Upload: trinhkhanh

Post on 10-Mar-2018

219 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

1

CS121/IS223 Week 3, Slide 1

CS121: Computer Programming I

Loops in Java

Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel

Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors (see the schedule posted on my webpage)

YOU MUST TRY THE EXAMPLES AND EXERCISES

CS121/IS223 Week 3, Slide 2

This week’s Agenda

•  More control structures in Java

•  Loops: –  while statements –  do-while statements –  for statements

•  Infinite loops

•  Nested loops

Basically these 3 statements do the same thing - you can rewrite loops using different statements, but sometimes one type looks neater than the others

CS121/IS223 Week 3, Slide 3

Controlling the Program Flow

•  Recall – an imperative program is a sequence of commands

•  Using conditional statements in a programming language: –  you can control the order in which these

commands are executed –  you can also control whether or not these

commands are actually executed

•  There are other ways to control the program flow…

CS121/IS223 Week 3, Slide 4

Control Structures - Recap

•  Flow of control is the order in which program statements are executed

•  Most programming languages have 2 kinds of statements to regulate flow of control: –  conditionals – branching/selection statements that

choose one set of statements over one or more other sets

–  loops – repeat a set of statements again & again until a stopping condition is reached

•  They often rely on boolean expressions

CS121/IS223 Week 3, Slide 5

Loops

•  A group of repeated statements

•  Loop body - group of statements to be repeated

•  Each repetition of a loop is called an iteration

•  Loop condition – mechanism for deciding when & how the repetition stops

One thing – many times!

CS121/IS223 Week 3, Slide 6

•  LOGO: http://el.media.mit.edu/logo-foundation/

Remember This?

Forward 50 Right 90 Forward 50 Right 90

Forward 50 Forward 50 Right 90 Right 90

Page 2: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

2

CS121/IS223 Week 3, Slide 7

My Variant of Turtle Commands

•  Assume your turtle can carry out the following commands: –  forward() – move 10 paces forward –  right() – turn 90 degrees to the right

•  Assume you can also ask your turtle a question: –  atGate() – your turtle answers true if he/she is in

front of a gate, false otherwise (remember Boolean flags)

A Boolean expression that is checked

E.g. adapted from [Winder & Roberts 1998] CS121/IS223 Week 3, Slide 8

A Simple Program

forward() right() forward() right() forward() right() forward()

•  Pick a starting point & then sketch out the path your turtle takes if he/she follows these commands faithfully

CS121/IS223 Week 3, Slide 9

Your Turtle’s Path

Start forward()

forward()

forward()

forward()

right()

right() right()

Correct? Statements in Turtle language are well defined and I ordered them!

CS121/IS223 Week 3, Slide 10

Same Program, Different Starting State

Start

forward()

forward()

forward()

right() right()

right()

Why is it important to be clear which way your turtle faces when he/she starts out?

forward()

Different starting conditions change outcomes of course!

CS121/IS223 Week 3, Slide 11

Getting from A to B

•  What sequence of commands do you need to give your turtle to get from A to B?

50 paces

20 paces

B

CS121/IS223 Week 3, Slide 12

Commands to Get From A to B

forward() forward() forward() forward() forward() right() right() right() forward() forward()

A

B

Page 3: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

3

CS121/IS223 Week 3, Slide 13

What Ifs?

•  What if: –  your turtle is facing another direction (e.g. West &

not East)? –  your turtle has a different starting position? –  the gate suddenly moves!

•  What if you want your program to get your turtle to the gate no matter where he/she starts, no matter what direction he/she faces, no matter where the door?

Remember – programming is about problem solving!

Your program sucks! It is hard-wired to solve ONE particular problem! What do you do?

CS121/IS223 Week 3, Slide 14

A Simple Sub-Problem

•  Get the turtle to the gate

•  Assumptions: –  turtle is always directly in front of & facing the gate –  no pitfalls between the turtle & the gate

•  Naïve solution: –  forward() … a suitable number of times –  need to change your program every time this

distance changes

What would we really like our program to do?

Changing the code EVERYTIME the context changes is not cool!

CS121/IS223 Week 3, Slide 15

Required Turtle Action

•  While our turtle is not at the gate, we would like him/her to move forward

•  We need to test whether our turtle is at the gate: atGate() ???

•  If our turtle is not at the gate, we want our turtle to: forward()

•  If our turtle is at the gate, we want our turtle to do nothing

CS121/IS223 Week 3, Slide 16

Your First Flavour of Loop

•  While turtle is not at the gate, move forward:

while (!atGate()){

forward();

}

Loop condition (test) – remember – this yields a boolean value

loop body – code you want executed if true

Kellogg's® Honey Nut Loops®

We get our turtle to the gate, however far away!

CS121/IS223 Week 3, Slide 17

The while Loop

while (!atGate()){ forward();

}

•  Asks the turtle whether he/she is at the gate – remember atGate() returns true if the turtle is at the gate & returns false if he/she is not at the gate

•  Then says, while condition NOT atGate() is true, move forwards: –  if atGate() is true, then not(atGate()) is false – the

loop body is not executed & the turtle does not move

–  if atGate() is false, then not(atGate()) is true - the loop body is executed. This means that the turtle executes a forward() command & the condition not(atGate()) is re-tested CS121/IS223 Week 3, Slide 18

The while Statement

•  while is a control statement: –  can control the way in which other statements are executed –  can control whether statements are executed at all

•  General structure: while <condition>{

doSomething(); }

•  doSomething() is executed only if the <condition> is true •  doSomething() will continue to be executed while the <condition> is

true – it keeps LOOPING!

if was also a control statement

Page 4: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

4

CS121/IS223 Week 3, Slide 19

More About while

•  The while statement allows for sequencing, iteration & repetition

•  Like the if statement, the while statement is based on Boolean expressions (i.e. testing whether things are true or false)

Terry the turtle will be back…

CS121/IS223 Week 3, Slide 20

while Loops in Java - the SYNTAX

while (condition){

statement1;

statement2;

}

•  Repeats loop body again & again until the condition becomes false

•  The loop body will be executed 0 or more times

Loop condition -boolean expression that evaluates to true or false

Loop body – simple or compound statements between {}

It tests the condition first and then executes the body if true

CS121/IS223 Week 3, Slide 21

Example

int count = 0;

while (count < 10){ System.out.println(“Number = ” + count);

count++;

}

Loop body generally contains something that changes the result of the controlling boolean expression (the loop condition) – here the value of count changes

What does this do?

Loop condition - evaluates to true or false

CS121/IS223 Week 3, Slide 22

Flowchart of Logic

count < 10 ?

count = count + 1

YES

NO

print…

CS121/IS223 Week 3, Slide 23

Result…

CS121/IS223 Week 3, Slide 24

Exercise

•  Write a Java program to countdown a rocket launch … e.g. 10, 9, 8, 7…..

•  Use a while loop

•  Get it to count down by steps of 2 •  Get it to count up and down at the same time :-)

Call your file Launch.java Think: Initial condition Stopping condition Step

Page 5: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

5

CS121/IS223 Week 3, Slide 25

Exercise

•  Write a Java program that asks the user to input a number & then uses a while loop to count up to that number, printing out all the whole numbers up to the number entered starting from zero

•  Then, count down from that number to zero

Call your file WhileCounter.java

CS121/IS223 Week 3, Slide 26

An Answer

Use Scanner for input

import java.util.Scanner; Scanner scan = new Scanner(System.in); int num; num = scan.nextInt();

If you see Keyboard anywhere, ignore it and use Scanner instead for input - Keyboard is Java legacy!!!

CS121/IS223 Week 3, Slide 27

do-while Loops in Java

do{

statement1;

statement2; }

while (condition);

•  The loop body will be executed 1 or more times - note how this differs from the while loop which may not execute at all

•  Termination condition follows the loop body

Boolean expression

Loop body

Need the ; to end the statement

Loop with attitude - just do it and ask questions later!

CS121/IS223 Week 3, Slide 28

Example

int count = 0;

do{ System.out.println(“Number = ” + count);

count++;

}while (count < 10);

What does this do?

CS121/IS223 Week 3, Slide 29

Flowchart of Logic

count < 10 ?

count = count + 1

YES

NO

print…

Good for dealing with user interaction

CS121/IS223 Week 3, Slide 30

Result…

Page 6: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

6

CS121/IS223 Week 3, Slide 31

Another Example

•  How could a while loop be used to control the operation of a casino jackpot machine?

Keep feeding money until you run out – write some pseudocode for this

CS121/IS223 Week 3, Slide 32

Jackpot Machine Version 1

totalCoins = 100

while totalCoins > 0: insertCoin() totalCoins = totalCoins - 1 winnings = pullLever() if winnings > 0: print “You Win!” totalCoins = totalCoins + winnings else: print “You loose!”

Initialise your variable

Give the loop a test condition (Boolean)

Loop

bod

y

Look!! We can put a conditional statement INSIDE a loop!

This is NOT Java…but my pseudocode - turn it into Java! You may need some things…

CS121/IS223 Week 3, Slide 33

Random Numbers - Useful Things!

•  Random is defined in the "java.util" library package, so any Java source file that uses Random must begin with:

import java.util.Random;

•  Initialize a random number generator a bit like you use Scanner: Random generator = new Random();

•  To generate a random integer: int r = generator.nextInt(); •  To generate a random real number: double r = generator.nextDouble(); •  So, to get a random number between 1 and 6 (e.g. for a die)

int roll = generator.nextInt(6) + 1; •  It gives you a number between 0 to 5, so you must +1 to get a

number between 1 to 6 to model a die

Experiment!

CS121/IS223 Week 3, Slide 34

Some Notes of Caution

•  With while loops: –  if the condition is initially false, the loop body is

never executed –  if there is nothing in the loop body to change the

value of the condition, the loop will not stop (infinite loop = BAD!)

–  if the condition is always true, the loop will not stop … unless you tell it to using a break statement (but this is sloppy practice)

•  You DO NOT want to write useless or infinite loops!

But you will when learning…so spot this!

CS121/IS223 Week 3, Slide 35

Exercise

•  Write a Java program to: –  prompt a user to enter a number –  keep asking the user to enter more numbers until

they enter the number 0 –  when 0 is entered, display the sum of all the

numbers entered

•  Hint: you will need to use: –  Scanner for input –  a variable to add up the numbers (accumulator) –  a while loop

Call your file Summing.java CS121/IS223 Week 3, Slide 36

Exercise

•  Now change this program to print out the product of all the numbers entered

•  Could you generate a random number to play a guessing game with the user?

Page 7: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

7

CS121/IS223 Week 3, Slide 37

Another Exercise

•  Write a Java program that: –  keeps on asking a user to enter a number until the

sum of the numbers entered is equal to or greater than 100

–  when that point is reached, stops asking for numbers & prints out whether the sum is 100 exactly or greater than 100

•  Note: with your loops, make sure you tie the value of the loop control variable to something you actually use to change the value of inside the loop!

Call your file Hundred.java

CS121/IS223 Week 3, Slide 38

Exercise

•  Write a Java program that asks the user to input a number & then uses a do-while loop to count up to that number, printing out all the whole numbers up to the number entered from zero

•  Then, count down from that number to zero

Call your file DoCounter.java

Think of a reason when you would *really* benefit from using this sort of loop rather

than a pure while loop…

CS121/IS223 Week 3, Slide 39

do-while Loops for UI

do{

enter a number

}

while (number not valid);

•  Good for dealing with the hazards of user input!

CS121/IS223 Week 3, Slide 40

An Answer What happens if the user enters 0? Fix this problem

Use Scanner for input

CS121/IS223 Week 3, Slide 41

Key Points (Interim)

•  Loops are a core programming construct

•  while loops are a way of controlling program flow

•  while loops are based on testing a condition & then executing statements (or not) based on the result

•  Something inside the while loop must make the value of the condition change – else we get stuck in an infinite loop!

CS121/IS223 Week 3, Slide 42

Code this…

Page 8: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

8

CS121/IS223 Week 3, Slide 43

Working Out in the Gym

•  If you go … what is ONE thing you do LOTS of in the gym???

Repetition!

Repetition!

Repetition!

Repetition!

CS121/IS223 Week 3, Slide 44

Working Out in the Gym

•  Would you write separate while loops to:

1.  Do 10 chin-ups

2.  Do 50 steps

3.  Lift dumbbells 15 times

4.  Do 100000 bench presses

On paper

CS121/IS223 Week 3, Slide 45

Doing 10 Chin-Ups

number = 0

while (number < 10): doChinUp() number = number + 1

----------------------------------------- number = 10

while (number > 0): doChinUp()

number = number - 1

Could count up

Could count down

This is Python code - but you should get the gist of what I am saying?

CS121/IS223 Week 3, Slide 46

Doing 50 Steps

number = 0

while (number < 50): doStep() number = number + 1

----------------------------------------- number = 50

while (number > 0): doStep()

number = number - 1

Counting up…

Counting down…

This is Python code - but you should get the gist of what I am saying?

CS121/IS223 Week 3, Slide 47

Lifting Dumbbells 15 Times

number = 0

while (number < 15): liftDumbbell() number = number + 1

----------------------------------------- number = 15

while (number > 0): liftDumbbell()

number = number - 1

Counting up…

Counting down…

Ditto - I use it as pseudocode

CS121/IS223 Week 3, Slide 48

Doing 100000 Bench Presses

number = 0

while (number < 100000): doPress() number = number + 1

----------------------------------------- number = 100000

while (number > 0): doPress()

number = number - 1

Counting up…

Counting down…

Ditto - I use it as pseudocode

Page 9: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

9

CS121/IS223 Week 3, Slide 49

Think!

•  while loops are sufficient for all our looping requirements

•  However - what have all these while loops got in common?

•  They each repeat an action a predefined number of times – the loop body either counts up to some known number, or counts down from some known number, using some pre-specified step

•  This is so common that we have a special type of loop for such situations

CS121/IS223 Week 3, Slide 50

for Loops

Kellogg's® Froot Loops®

CS121/IS223 Week 3, Slide 51

for Loops in Java SYNTAX

for (start; stop; incr/decr){

statement1; statement2;

}

•  Count from start to stop by a specified increment/decrement step - - eh?

•  Does same thing as other loops, but looks neater

•  Great for when you know how many times you want to repeat

Boolean expression

Loop body

Increment/decrement

CS121/IS223 Week 3, Slide 52

Example

for (int count=0; count < 10; count++){

System.out.println(count);

}

Loop control variable is called count count is declared to be an integer and given an initial value of 0

CS121/IS223 Week 3, Slide 53

Example

for (int count=0; count < 10; count++){

System.out.println(count);

}

Check if the value of the variable count is less than 10

If the value of count is less than 10, execute the loop body - this means - execute the println statement

If the value of count is not less than 10, then the loop is exited… and control passes to after the }

CS121/IS223 Week 3, Slide 54

Example

for (int count=0; count < 10; count++){

System.out.println(count);

}

After the loop body has been executed, add 1 to the current value of count (increment)

Note - if the loop exited - count is not incremented

Page 10: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

10

CS121/IS223 Week 3, Slide 55

Example

for (int count=0; count < 10; count++){

System.out.println(count);

}

Now check if count is less than 10

If less than 10, execute loop body, increment the value of count etc. If not less than 10, exit …and so on…

CS121/IS223 Week 3, Slide 56

Example

for (int count=0; count < 10; count++){

System.out.println(count);

}

•  Start at 0, count up by 1 while less than 10 •  Increment done after executed the loop body –

prints 0-9

Loops can often be written without braces when a single statement is in the loop body – but best practice is to always use braces as it is clearer to read

CS121/IS223 Week 3, Slide 57

Result…

CS121/IS223 Week 3, Slide 58

Example

for (int count = 1; count < 11; count ++){

System.out.println(count);

}

•  Start at 1, count up by 1 while less than 11

•  Increment done after executed the loop body – prints 1-10

Important: count value is incremented after the loop body has been executed, not before

CS121/IS223 Week 3, Slide 59

Result…

CS121/IS223 Week 3, Slide 60

Flowchart of Logic

count < 11 ?

count = count +1

YES

NO

print…

count = 1

Page 11: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

11

CS121/IS223 Week 3, Slide 61

Exercise

•  Write a Java program that uses a for loop to print out all odd numbers between 1 & 10 (inclusive)

•  Write a Java program that uses a for loop to count down from 10 to zero (blast off!) & print this out

Call your file OddCounter.java

Call your file BlastOff.java

CS121/IS223 Week 3, Slide 62

An Answer

CS121/IS223 Week 3, Slide 63

An Answer

CS121/IS223 Week 3, Slide 64

Exercise

•  Write a Java program to print out the 12 times table, between 0 & 12: 0*12 = 0 1*12 = 12 2*12 = 24 etc…

•  Use a for loop

Call your file Tables.java

RHS: what general expression gives us this value? LHS: what value changes & what value stays the same & how can you tie the one that changes to your loop control variable?

CS121/IS223 Week 3, Slide 65

Exercise

•  Write a Java program to: –  ask a user to enter a number between 1 & 25 –  check for valid input using a conditional –  print the entered number of * characters on a

single line (if valid) –  DO NOT use “*” * number!!!

•  Use a for loop

Call your file Characters.java

CS121/IS223 Week 3, Slide 66

Exercise

•  Write a loop to work out the factorial of any POSITIVE integer

•  Which loop would you use? A while or a for loop?

•  What is a factorial? 5! = 1 * 2 * 3 * 4 * 5 = 120 n! = n * (n-1) * (n-2) … * 1

•  If you are stuck – try writing a loop to just calculate 5! – but you must use a loop

Call your program Factorial1.java

Page 12: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

12

CS121/IS223 Week 3, Slide 67

Hint for Use

•  A While loop is useful when we don't know how many times a loop is to be executed - non-deterministic

•  A For loop is good when you do know - deterministic

CS121/IS223 Week 3, Slide 68

Key Points (Interim)

•  Loops are a really core programming construct

•  for loops are a way of controlling program flow

•  for loops are based on specifying a starting condition, ending condition & stepping factor

•  The main difference between while loops & for loops: –  while loops repeat an unspecified number of

times & are good for when the step size varies –  for loops repeat a specified number of times &

are good for when the step size is consistent

CS121/IS223 Week 3, Slide 69

Infinite Loops

•  You must ensure your loops eventually terminate: –  loop conditions must eventually become false

•  Example: int count = 0;

while (count < 10){

doSomething();

count--;

}

Can you see why this never stops?

CS121/IS223 Week 3, Slide 70

Exercise

•  Which of these are infinite loops? What could you do to make them terminate?

int count = 0;

while (count !=10)

count +=3;

int count = 1;

while (count!=10)

count ++;

int count = 0;

while (count !=10)

count +=2;

int count = 1;

while (count > 1)

count ++;

Nifty: count+=3 is the same as count=count+3 count++ is the same as count=count+1

CS121/IS223 Week 3, Slide 71

Nested Loops

•  When the body of a loop contains another loop

•  Example: int count1 = 1, count2; while (count1 <= 10){

count2 = 1; while (count2 <= 20){ System.out.println("*");

count2++; }

count1++; }

How many *?

CS121/IS223 Week 3, Slide 72

Exercise

•  Why does this code not terminate?

int count1 = 1, count2;

while (count1 <= 10){

count2 = 1;

while (count2 <=20){ System.out.println("*");

count1++;

} count2++;

}

Page 13: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

13

CS121/IS223 Week 3, Slide 73

Odd Loops Confusing You?

CS121/IS223 Week 3, Slide 74

Help is at Hand

Terry’s back in town!

CS121/IS223 Week 3, Slide 75

Loops Within Loops

•  while loops within while loops

•  for loops within for loops

•  while loops inside for loops

•  for loops inside while loops

CS121/IS223 Week 3, Slide 76

Terry the Turtle Returns

while not(atGate()):

forwardMarch()

•  Terry can now cope with the following scenario … but wants to do better!

Not Java syntax - this is just for illustration!

CS121/IS223 Week 3, Slide 77

The Next Problem

•  Still get the turtle to the gate

•  Different assumptions: –  turtle can start facing any direction –  turtle is now in a fenced

field with 4 sides, 1 gate & no pitfalls

Find an algorithm

CS121/IS223 Week 3, Slide 78

One Way…

What’s the pseudocode?

Page 14: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

14

CS121/IS223 Week 3, Slide 79

Try to Code the Algorithm

•  Assume your turtle can STILL carry out the following commands: –  forward() – move 10 paces forward –  right() – turn 90 degrees to the right

•  Assume you can also ask your turtle questions: –  atGate()? – your turtle answers true in he/she is next to a

gate (in front of, left of, right of), false otherwise –  canGoForward()? – your turtle answers true if he/she

can move forwards, false otherwise

Cond

ition

als

E.g. adapted from [Winder & Roberts 1998]

New command CS121/IS223 Week 3, Slide 80

Moving To & Along the Fence

while canGoForward(): forward()

right()

while canGoForward(): forward()

right()

…etc

How many times do we write this?

When does it stop?

CS121/IS223 Week 3, Slide 81

A Nested while loop

while not(atGate()):

while canGoForward():

forward()

right()

Does this work?

CS121/IS223 Week 3, Slide 82

Better Loop Conditions

while not(atGate()):

while (not(atGate()) and canGoForward()):

forward()

right() Does this work okay?

CS121/IS223 Week 3, Slide 83

Better Loop Conditions

while not(atGate()):

right()

while (not(atGate()) and canGoForward()):

forward()

Does this handle pitfalls?

CS121/IS223 Week 3, Slide 84

A Nested for Loop

•  Doing 3 sets of 15 reps at the qym:

for number in range (3):

for number in range (15):

doChinUp()

This is Python code - but you should get the gist of what I am saying?

Page 15: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

15

CS121/IS223 Week 3, Slide 85

A for Loop Inside a while Loop

while (not tired()):

for number in range (15): doChinUp()

rest 30 seconds tired = tiredYet()

Keep doing reps of 15 until zonked!

Ditto

CS121/IS223 Week 3, Slide 86

A while Loop Inside a for Loop

for guest in range(4):

while not bowlFull(guest):

putScoopInBowl(guest)

Assumes a never ending supply of ice cream!

Ditto

CS121/IS223 Week 3, Slide 87

Exercise - Nested for Loop

•  Write a Java program that: –  prints out a 10 * 5 rectangle of characters –  e.g.

********** ********** ********** ********** **********

–  using a nested for loop

Call your program Box.java

Pseudocode first!

********** * * * * * * **********

--Then make it ANY size --Then make it border only

CS121/IS223 Week 3, Slide 88

Exercise - Nested while Loop

•  Write a Java program that copies your music from CDs on to your iPod: –  assume you have 1G of disk space (small!) –  use an outer while loop to keep getting new CDs until you

run out of disk space –  use an inner while loop to keep asking for the track length

of the different tracks on a single CD until there are no tracks left to copy

–  you will need the user to type in a dummy number (called a sentinel number) when there are no more tracks left to copy from each CD

–  Just try to model the behaviour as you can…many ways…

Call your program Pod.java

Pseudocode first!

CS121/IS223 Week 3, Slide 89

Exercise - for Loop Inside a while Loop

•  Write a Java program that plays 21 with a user: –  use a while loop to keep playing the game until

the user wins (has 21) –  ask a user how many cards they want dealt –  use a for loop inside the while loop to prompt

the user to enter the value of each of their cards one at a time – or generate automatically using a random number

Call your file Poker.java

Try to fix it to only accept hands of 2 or more cards & only accepts valid card values

Pseudocode first!

CS121/IS223 Week 3, Slide 90

Exercise - while Loop Inside a for Loop

•  Write a Java program that builds a wall 5 feet long & 4 bricks high. The bricks are broken & of varying length, either 10, 11 or 12 inches long: –  use a for to step through the layers in the brick

wall (4 layers) –  use a while loop inside the for loop to prompt

the user for the length of each brick –  assume the user enters a valid brick length –  don’t worry if the wall is uneven at the edge

Call your program Bricks.java

Try to fix it to only accept bricks of specified size. Also, generalise it to ask a user how many layers they want to build & only build that many

Pseudocode first!

Page 16: CS121: Computer Programming I This week’s Agendacsis.pace.edu/~ogotel/teaching/cs121_week3_spring09_small.pdf · CS121: Computer Programming I Loops in Java ... CS121/IS223 Week

16

CS121/IS223 Week 3, Slide 91

Next Task

•  Remember the game flowchart – the Fire Demon game?

•  You should now write the code to play this game – you have all the control structures you need to form a basic working program

•  The only thing you don’t have is the timer… so see if you can research and figure that out

CS121/IS223 Week 3, Slide 92

Key Points (More…)

•  Loops can be nested within loops to an arbitrary level of depth

•  While is is sometimes necessary to write nested loops, these can get messy & unreadable – the program flow can get VERY confusing

•  If you nest your loops, nest them with care

•  Make sure your loops STOP!

CS121/IS223 Week 3, Slide 93

Key Points

•  The body of while loops may be iterated zero or more times

•  The body of do-while loops are executed at least once (they just do it regardless!)

•  A for loop is basically another way of writing a while loop & is great for counting

•  Count-controlled loops / ask-before iterating loops •  Loop components:

–  initialisation statements –  loop body –  termination mechanism (condition)

When in doubt, use a while CS121/IS223 Week 3, Slide 94

Before Next Time…

•  Reading: –  if 3rd edition - read Chapter 3.1-3.9 of the Java book –  if 4th-6th edition – read Chapter 5.1-5.8 of the Java book –  think about it, make brief notes, ask questions & follow up

things that confuse you –  make sure you run the example code & understand the

answers to the self-review questions

•  Continue with Java Exercise Sheet 1 (make sure you can do parts C & D before the end of Feb)

•  Try to do all the exercises on the slides – the only way to learn is to practice

Java project… remember... I want to see your design in class on Feb 17

CS121/IS223 Week 3, Slide 95

Coming Up Next Week

•  Don’t worry – loops are hard at first – so we will get to practice with all these things in class next week

•  More practice with control structures in Java

•  Some additional concepts associated with control structures

•  TEST soon – Java basics & control structures – so practice!

CS121/IS223 Week 3, Slide 96

IMPORTANT NOTICE!

•  This can all be quite confusing and difficult to learn for the first time! Be patient and be persistent!

•  But - you must practice, experiment and try things out (you cannot just read slides and text books)

•  So, get coding … if you can code the fire demon game then designing and coding your own project will be easy… but it will take a lot of hard work getting this all figured out. Allocate time!