Docsity

More Control Structures in Java, Loops, Infinite Loops, Nested Loops | CS 121, Exams of Computer Science

Toggle sidebar
bg1
1
CS121/IS223 Week 3, Slide 1
CS121: Computer Programming I
Loops in Java
Dr Olly Gotel
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
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download More Control Structures in Java, Loops, Infinite Loops, Nested Loops | CS 121 and more Exams Computer Science in PDF only on Docsity!

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 Right 90 Forward 50 Right 90

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

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

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…

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…

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

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-

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

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 +

YES

NO

print…

count = 1

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:

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?

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

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?

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

Conditionals

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?

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 3 rd edition - read Chapter 3.1-3.9 of the Java book
    • if 4 th- 6 th 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!