30
CMP-MX21: Lecture 5 Repetitions Steve Hordley

CMP-MX21: Lecture 5 Repetitions

  • Upload
    petula

  • View
    22

  • Download
    0

Embed Size (px)

DESCRIPTION

CMP-MX21: Lecture 5 Repetitions. Steve Hordley. Overview. 1. Repetition using the do-while construct. 2. Repetition using the while construct. 3. Repetition using the for construct. A problem. - PowerPoint PPT Presentation

Citation preview

Page 1: CMP-MX21: Lecture 5 Repetitions

CMP-MX21: Lecture 5

Repetitions

Steve Hordley

Page 2: CMP-MX21: Lecture 5 Repetitions

Overview

1. Repetition using the do-while construct

2. Repetition using the while construct

3. Repetition using the for construct

Page 3: CMP-MX21: Lecture 5 Repetitions

A problem

The calculator program we developed in the previous lectures allows us to perform a single operation on two numbers. We would like to extend the program so that we can repeatedly perform operations on different numbers until the user decides to exit the program.

Here, the problem we must address is how we can repeat a set of instructions two or more times. In this lecture we will look at three different JAVA constructs which help us solve this task.

Page 4: CMP-MX21: Lecture 5 Repetitions

Designing a solution

1. Read two numbers from the keyboard

2. Read an “operation” from the keyboard

3. Apply the operation to the two numbers

4. Write out the result

5. Ask the user if they wish to continue

6. If answer is yes, goto step 1, otherwise stop

The basic elements of our program will not change very much: it is still performing the same basic operations, but multiple times. The modified program flow will be something like this:

Page 5: CMP-MX21: Lecture 5 Repetitions

Designing a solution

The program flow can be visualised like this:

...

statements;

...

Evaluate expression

statements;

expression false

expression false

Page 6: CMP-MX21: Lecture 5 Repetitions

The do-while construct

In JAVA, this program flow is achieved with the do-while construct:

...

do{

statements;

} while (expression);

...

The do keyword denotes the start of a block of statements

which might be repeatedStatements after the

do are performed

When the while keyword is reached

expression is evaluated

If expression is true, the program returns to the first statement after the do

Otherwise, execution continues after the while

Page 7: CMP-MX21: Lecture 5 Repetitions

An example

...

do{

char theAnswer;

// Read two numbers

// Read an operator

// Perform the operation and display the result

System.out.println(“Another operation [y/n]?”);

theAnswer = Keyboard.readChar();

} while (theAnswer == ‘y’);

...

We can modify our calculator program to allow multiple operations using a do-while construct:

Page 8: CMP-MX21: Lecture 5 Repetitions

Some notes

If we want to repeat only a single statement we don’t need the curly brackets:

...

do

statement;

while (expression);

...

Once we have more than a single statement between the do and the while, then curly brackets are required.

Page 9: CMP-MX21: Lecture 5 Repetitions

Other repetition constructs

The statements between the do and the while in the do-while construct are always executed at least once

This is because the test for repetition (the while (expression)) comes after the block of statements

Sometimes, we want to repeat a block of statements zero or more times depending on some condition. In this case we need the test before the statement block ...

Page 10: CMP-MX21: Lecture 5 Repetitions

The while construct

The while construct allows us to deal with this situation:

...

while (expression){

statements;

}

...

When the while keyword is reached, expression is

evaluated

If expression is true, the statements between the

curly brackets are executed and the program then returns to the while

statement

Otherwise, program execution continues after

the closing bracket

Page 11: CMP-MX21: Lecture 5 Repetitions

An example

...

System.out.println(“Perform an operation [y/n]?”);

theAnswer = Keyboard.readChar();

while (theAnswer == ‘y’) {

// Read two numbers

// Read an operator

// Perform the operation and display the result

}

...

We can modify the calculator program so that it asks whether an operation is to be performed, each time, including the first:

Page 12: CMP-MX21: Lecture 5 Repetitions

Some notes

The while construct does not have a do associated with it

The expression in both the while and the do-while construct must return a boolean value (true or false)

In both constructs we should take care to choose the expression carefully (and write it correctly) otherwise problems may result

Page 13: CMP-MX21: Lecture 5 Repetitions

Some common errors

int i=1;

while (i<4){

System.out.println(“i=1”+i);

}

The expression in this control loop will always evaluate to true. The result is that the program runs until the computer runs out of memory (or possibly forever):

i = 1i = 1i = 1…stack overflow…

Page 14: CMP-MX21: Lecture 5 Repetitions

Some common errors

int i=0;

while (i>0){

System.out.println(“i=1”+i++);

}

The expression in this control loop will always evaluate to false so the statement in the loop will never be executed.

Page 15: CMP-MX21: Lecture 5 Repetitions

The for construct

The two loop constructs seen so far execute a set of statements some variable number of times.

Sometimes we know in advance how many times we wish to execute a set of statements.

JAVA provides a third construct: the for construct for these situations

Page 16: CMP-MX21: Lecture 5 Repetitions

The for construct

...

for (initialiser; condition; change){

statements;

}

...

The for construct has the following general form:

An expression evaluated once, when the for is

first encountered

An expression evaluated before each cycle of the

loop

An expression evaluated at the

end of each cycle of the loop

Page 17: CMP-MX21: Lecture 5 Repetitions

The for construct

The for has the following flow: initialiser

Evaluate “condition”

execute loop statements

Evaluate “change”

Next program statement

true

false

Page 18: CMP-MX21: Lecture 5 Repetitions

An example

...

for (int i=0; i<4; i++){

System.out.println(“i=“+i);

}

...

i=0

i=1

i=2

i=3

Outputs:

Page 19: CMP-MX21: Lecture 5 Repetitions

The for loop

int i=0;

while (i<4){

System.out.println(“i=“+i);

i++;

}

We can re-write any for loop as a while construct. E.g. the previous example:

Initialisation is performed first

Condition is tested

If condition is true, statements are

performed

Change expression is evaluated

Page 20: CMP-MX21: Lecture 5 Repetitions

A second example

Suppose we wish to calculate xn (x to the power of n). This can be done with the following for construct:

for (r=1.0, i=1; i<=n; i++)

r*=x;

In this example, two initialisations are performed: r=1.0 and i=1. Multiple initialisations are separated by commas

Any of the three parts of the for can have multiple expressions. These expressions must be separated by a comma.

Page 21: CMP-MX21: Lecture 5 Repetitions

A second example

for (r=1.0, i=1; i<=n; i++, r*=x)

;

In this case no statement is executed after the for. This is denoted by the semi-colon on its own.

The previous example could also be written like this:

Page 22: CMP-MX21: Lecture 5 Repetitions

Some notes

Any of the initialisation, condition, and change can be omitted from the for:

r=1.0;

i=1;

for (; i<=n; i++, r*=x)

;

Note that the semi-colon separating these three elements must remain: all for constructs have two semi-colons

Page 23: CMP-MX21: Lecture 5 Repetitions

Some notes

for (;;)

System.out.println(“This loops for ever”);

We can even leave all three elements out of the construct:

Note, if there is no condition, it will be regarded as true

So, if our for loop doesn’t contain a condition we need an alternative method to terminate the loop

Page 24: CMP-MX21: Lecture 5 Repetitions

Terminating loops

The break statement can be used to terminate a loop:

for (i=1;;){

System.out.println(“i=”+i++);

if (i==5)

break;

}

The break statement causes program execution to jump to the first statement after the end of the loop

The break statement can be used in a for, a do-while, or a while construct

Page 25: CMP-MX21: Lecture 5 Repetitions

Terminating loops

The continue statement causes program execution to jump to the beginning of the next loop:

for (i=1;i<=5;i++){

if (i==3)

continue;

System.out.println(“i=”+i++);

}

i=1

i=2

i=4

i=5

Page 26: CMP-MX21: Lecture 5 Repetitions

Some common errors

for (i=1;i<=5;i++);

System.out.println(“i=”+i++);

i=6

Putting a semi-colon at the end of the for statement means that no statements are to be executed at each loop. The change expression and the condition are still evaluated until the condition becomes false

Then the statements after the for will be executed

Page 27: CMP-MX21: Lecture 5 Repetitions

Some common errors

Like the do-while and while loops, we need to be careful with the condition statement in a for loop:

for (i=10;i<=5;i--)

System.out.println(“i=”+i++);

Here the condition is false from the start so the loop never gets executed

Page 28: CMP-MX21: Lecture 5 Repetitions

Some common errors

for (i=10;i>5;i++)

System.out.println(“i=”+i++);

i=10

i=11

i=12

...

stack overflow error

Here the condition is always true so the loop will continue until the system runs out of resources (or forever)

Page 29: CMP-MX21: Lecture 5 Repetitions

A summary

In this lecture we have introduced three JAVA constructs for repetition: the while, the do-while, and the for

We have also seen how to exit from program loops using the break and continue statements

Page 30: CMP-MX21: Lecture 5 Repetitions

A summary

You should now be familiar with the meaning of the following words from the JAVA language:

do, while, for, continue, break