Control Flow Statements
Control Flow Statements
Control Flow Statements
- The statements inside your source files are generally executed from top to
bottom, in the order that they appear. We have run programs wherein
statements are executed one after another in a fixed order.
if (boolean _expression){
statement 1;
statement2;
….}
if (boolean__expression) {
-indent- statement1;
-indent- statement2;
}
if – else statement
- The if – else statement is used when we want to execute a certain
statement if a condition is true, and a different statement if the condition
is false.
if (boolean_expression)
statement;
else
statement;
if (boolean_expression) {
statement1;
statement2;
….}
else {
statement1;
statement2;
….}
Coding guidelines:
B. You can have nested if – else blocks. This means that you can have other
if – else blocks inside another if – else block. For example,
if(boolean_expression){
if(boolean_expression){
….
}
}
else{….
}
if – else – if statement
- The statement in the else – clause of an if – else block can be another if –
else structures. This cascading of structures allows us to make more
complex selections.
if(boolean_expression1)
statement1;
else
if (boolean_expression2)
statement2;
else
statement3;
For example,
Looping Statements
- In the programs we have written so far, the statements in the program
have been executed in sequence, from the start of the program to the
end, omitting sections of "if" and "switch" constructs which have not been
selected. The real power of computers comes from their ability to execute
given sets of statements many times, commonly known as looping.
Why Looping?
(i) To automate the repetition of calculations. We wish to repeat the
calculation once for each one of a number of items of data. We may wish
to compute the profit for a number of different months of a company's sales.
We may wish to compute the stress in each part of the structure of a bridge.
We may wish to look at each word in a file of text. In some cases, we may
know in advance exactly how many times the calculation will need to be
repeated.
● (ii) To iterate through data and test for certain condition. For example, we
may read numbers from a keyboard, analyse each one and perform
some action on it, until a particular value is typed. Another example is that
many computer programs keep reading commands and executing them
until the user types "quit". In this case, we do not know in advance how
many times we will have to go round the loop.
(iii).To keep attempting for some operation (such as obtaining data from a
remote computer over a network) until either we succeed (all is well, we
have obtained the data, so we proceed to use that data), or until a
specified number of attempts have failed. (In this case the whole process
must be abandoned.)
"while" loops
Syntax:
while (condition)
statement;
The sequence of operations in the loop (after the initialisation of the value of
"Number" to 10, for example) is :
(ii) If it is FALSE, abandon the loop, and continue with the statements
after the closing curly brace. In this case, the next statement to
be executed
would print out the "Loop ended" message.
(iii) If the result of "Number >= 0" is TRUE, execute the statements in
the body of the loop (between the curly braces, in this case first
print a message, and then decrement the value of "Number" by 1
), and then return to step (i) above.
- The test is TRUE to continue the loop, FALSE to leave it. The test occurs
before the loop is executed; the loop may not be executed at all if the
test result is FALSE the very first time that it is encountered. The pattern of
execution is thus
test;
or
test; loop; test;
or
test; loop; test; loop, test;
and so on. The last test on each line must have delivered the result FALSE;
earlier tests must have delivered the result TRUE.
- When the loop finishes, control passes to the next instruction in the
program, following the closing curly brace of the loop.
// version 1
int Number = 1;
while ( Number <= 10 ) {
System.out.println( Number );
....;
Number++;
}
//version 2
int Number = 0;
while ( Number < 10 ) {
Number++;
System.out.println( Number );
....;
}
// Version 3
int Number = 0;
while ( Number++ < 10 ) {
System.out.println( Number );
....;
}
// Version 4
int Number = 0;
while ( ++Number <= 10 ) {
System.out.println( Number );
....;
}
Points to observe
Note 1: If what you really want is to execute the loop 10 times, write the
condition (as above) Number < 10 and not as Number <= 9
Note 2 : In general, specific values such as "10" should not appear within the
body of your program. They would probably be needed in more than one
place, since you may have several loops processing the same number of
data items. You should therefore declare them as finals at the top of the
program as typified by the example :
The CourseMaster marking system checks that constant values other than,
for example "0" and "1" do not appear in the body of the program, and
appear exactly once in a "constant" declaration.
Note 3 : In Java generally you would more likely want to loop not from 1 to
10, but from 0 to 9. All counting in Java tends to start at zero rather than one.
This is a convention that most Java programmers adopt.
Infinite Loops
- The body of a while loop must eventually make the condition false
- If not, it is an infinite loop, which will execute until the user interrupts the
program
- This is a common type of logical error -- always double check that your
loops will terminate normally
int counter = 1
while (counter>0) {
System.out.println("Counter:" + counter);
counter++;
}
● To add together the sequence 1 + 1/2 + 1/4 + 1/8 + ... until the terms we
are
adding together are smaller than 0.00001
● The value of "Term" is halved each time round the loop; each of these
values is added to the total.
● For debugging we suggest that you put a print statement inside the loop,
such as System.out.println( Total + " " + Term ); to verify that the loop is
functioning correctly. You can delete this line later, or simple put a "//" at
the start of it.
● To read positive integer numbers in, terminated by a zero, and print the
biggest one:
int NextNumber = 1, Biggest = 0;
while ( NextNumber != 0 ) {
NextNumber = UserInput.getInt();
if ( NextNumber > Biggest ) {
Biggest = NextNumber;
}
} // end while NextNumber non-zero
System.out.println( "Biggest was " + Biggest );
● Note the following possible alternative coding, which has the drawback
that the input instruction has to be repeated.
● Within the loop, we read the next number at the end of the loop. We must
read the very first number before we enter the loop.
“do” loops
Syntax:
[initialization]
do {
[statements]
[iteration]
} while ( boolean-expression )
- The "while" loops above performed the test first, and then executed the
loop. Sometimes you may wish to test at the end of the loop, after the
execution of the statements in the body of the loop (and hence to
execute the loop body always at least once). In JAVA we use what is
referred to as a "do" loop, written as follows :
int Number = 1;
do {
....;
Number++;
} while ( Number <= 10 );
o In this case the value of "Number" would be 1 the first time round
the loop, and 10 the last time. The condition (exactly as in a "while"
loop) is still contained in round brackets, and is still TRUE to continue
with another execution of the loop body, and FALSE to leave the
loop. Remember that there is a semicolon after the condition,
terminating the whole statement. We have one more semicolon
overall than the equivalent "while" loop.
- This is the form of combined "increment and test" that most C++
programmers that write JAVA would use. The "++" must, of course, be in
front of the "Number" in this case.
- It is generally safer to test at the start of a loop;
- "while" loops are generally safer and more common than "do" loops.
- We may wish to abandon the program from within the body of the loop if
some error condition occurs.
int NextNumber;
do {
NextNumber = UserInput.readInt();
if ( NextNumber < 0 ) {
System.out.println( "Error, negative number" );
System.out.println( "Value " + NextNumber );
System.exit( -1 );
}
.. process the number ..
.. which must be >= 0 ..
} while ( NextNumber > 0 );
"for" loops
Syntax:
for ([ initialization ];
[ boolean-expression ];
[iteration]) {
[statements] }
Examples:
- It is common to declare the loop variable at the start of the for loop itself:
for ( int Count = 0; Count < 10; Count++ ) {
....;}
- The general form of a "for" loop is:
- The initialise statement is carried out once only, at the start of the first time
that the loop is entered.
- The test is executed before each execution of the body of the loop,
including a test before the very first execution of the loop.
- The first time will be immediately after the initialisation, and hence there
will be perhaps no executions of the loop body if the test fails at this stage.
- Again note that the increments in the examples above could be written
with the "++" before or after the variable identifier; in this case it does not
matter.
- One of the important advantages of a "for" loop is its readability. All of the
essential loop control is grouped together at the top of the loop. We can
see at a glance the initial values which are set up, the test to be satisfied
for loop exit, and the main variable increments. You should make
maximum use of this readability.
Defaults
for (
this = 10, that = 0;
this > that;
this--, that++
){
....;}
- The loop executes with "month" and "year" taking the pairs of values
[1900,0], [1900,1], [1900,2], ..., [1900,11], [1901,0], [1901,1], ..., [1901,11], ...,
[1999,11] in turn in that order.
- In any of the above loops, the special statement "break" causes the loop
to be abandoned, and execution continues following the closing curly
brace.
while ( i > 0 ) {
....;
if ( j == .... ) {
break; // abandon the loop
} ....;
} // end of the loop body
System.out.println( "continues here ...");
- In any of the above loops, the statement "continue" causes the rest of the
current round of the loop to be skipped, and a "while" or "do" loop moves
directly to the next test at the head or foot of the loop, respectively;
- a "for" loop moves to the increment expression, and then to the test.
- Note that labelled break and continue are available but beyond the
scope of this course.
- We wish to write a loop processing integer values which we have read in.
If the value we have read is negative, we wish to print an error message
and abandon the loop. If the value read is greater than 100, we wish to
ignore it and continue to the next value in the data. If the value is zero,
we wish to terminate the loop.
-
while ( ( value = UserInput.readInt() ) != 0 ) {
if ( value < 0 ) {
System.out.println( "Illegal value");
break; // Abandon the loop
}
if ( value > 100 ) {
System.out.println( "Invalid value");
continue; // Skip to start loop again
}
// Process the value read
// guaranteed between 1 and 100
....;
....;
} // end while value != 0
“for” loops
Curly braces: If there is only a single statement in the loop body, the curly
braces are not obligatory in JAVA. It is however recommended that you
always use them.
int count = 0;
float maximum = 0.0f, minimum = Float.MIN_VALUE;
float Total = 0.0f, Number;
System.out.println( "Type positive values ");
System.out.print( "ended by zero or negative: ");
while (( Number= UserInput.readFloat()) > 0 ){
Total += Number; // add numbers together
if ( minimum > Number ) { // check minimum so far
minimum = Number;
}
if ( maximum < Number ) { // check maximum
maximum = Number;
}
count++; // count numbers
} // while Number > 0
System.out.println(Total + " " + count );
System.out.println("Min: " + minimum + "Max: " + maximum);
● Be careful if you wish to print the average of the numbers, and use
if ( count > 0 ) {
System.out.println( "Ave " + Total / count );
} else {
System.out.println( "No data to average");
} // end if count > 0
● You must ensure that you can never attempt a division by zero. Wherever
there is a division sign in a program you must be able to prove that the
denominator cannot be zero.
Sum of squares
int sum = 0;
// add squares up to 99 squared
for ( int nextVal = 1; nextVal < 100; nextVal++ ) {
sum = sum + nextVal * nextVal;
}
System.out.println( "Sum of 1*1+2*2+..+99*99=" + sum);
Decreasing powers of 2
- To print (in decimal) the decreasing powers of 2 (1, 1/2, 1/4, 1/8, ...) you
would write:
int count = 1;
final float LIMIT = 0.00001f;
for ( float x = 1.0f; x > LIMIT; x *= 0.5f,count++ ) {
System.out.println( "Count " + count + ", x " + x );
}
Reading Characters
char ch;
int count = 0;
while ( ( ch = UserInput.readChar() )!= '.‘ ) {
if ( ch == 'e' || ch == 'E' ) {
count++;
}
} // end while ch != '.'
System.out.println( "There were " + count + “
letter e's");
- Read a series of integers, zero terminated, and print how many times an
integer was larger than its predecessor, and how many times it was
smaller. Ignore the terminating zero.
int next, previous;
int bigger = 0, smaller = 0;
previous = UserInput.readInt(); // Set up the first value
// Read data up to a zero
while (( next = UserInput.readInt()) != 0 ) {
if ( next > previous ) { // Was it bigger than previous?
bigger++;
}
if ( next < previous ) { // Was it smaller?
smaller++;
}
previous = next; // Store this value for next loop
}
System.out.println( "Bigger " + bigger );
System.out.println( "Smaller " + smaller );
Summary
Looping
Introduction
While loops
Syntax
Examples
Points to Observe
Infinite Loops
Examples using while loops
do..while loops
Examples
Exiting
For loops
Definition
Examples
Readability
Nesting
Break - Continue
Looping Examples
Decreasing powers of 2
Reading Characters
Increasing and Decreasing Integers