CMP-MX21: Lecture 5 Repetitions
description
Transcript of CMP-MX21: Lecture 5 Repetitions
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
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.
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:
Designing a solution
The program flow can be visualised like this:
...
statements;
...
Evaluate expression
statements;
expression false
expression false
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
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:
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.
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 ...
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
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:
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
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…
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.
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
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
The for construct
The for has the following flow: initialiser
Evaluate “condition”
execute loop statements
Evaluate “change”
Next program statement
true
false
An example
...
for (int i=0; i<4; i++){
System.out.println(“i=“+i);
}
...
i=0
i=1
i=2
i=3
Outputs:
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
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.
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:
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
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
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
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
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
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
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)
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
A summary
You should now be familiar with the meaning of the following words from the JAVA language:
do, while, for, continue, break