Control Flow Statements

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

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.

- Control flow statements, however, break up the flow of execution by


employing decision making, looping, and branching, enabling your
program to conditionally execute particular blocks of code.

There are two types of control structures:


A. Decision control structures
- Allows us to select specific sections of code to be executed

B. Repetition control structures


- Allows us to execute specific sections of the code a number of times

*Decision Control Structures


if statement
- The if statement specifies that a statement (or block of code) will be
executed if and only if a certain boolean statement is true.

The if – statement has the form,

if (boolean _expression){
statement 1;
statement2;
….}

Where Boolean expression is either a boolean expression or boolean variable.

Example, given the code snippet:

int grade = 68;


if (grade > 60)
System.out.println (“Congratulations!”);
Or,
int grade = 68;
if (grade>60) {
System.out.println (“Congratulations!”);
System.out.println (“You passed!”);
}
Coding guidelines

A. The boolean__expression part of a statement should evaluate to a


boolean value, that means that the execution of the condition should
either result to a value of true or false.

B. Indent the statements inside the if – block. For example,

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.

The if – else statement has the form:

if (boolean_expression)
statement;
else
statement;

or can also be written as,

if (boolean_expression) {
statement1;
statement2;
….}
else {
statement1;
statement2;
….}

For example given the code snippet:

int grade = 68;


if (grade>68)
System.out.println(“Congratulations!”);
else
System.out.println(“Sorry, you failed!”);
Or,

int grade = 68;


if (grade>60) {
System.out.println(“Congratulations!”);
System.out.println(“You passed!”);}
else{
System.out.println (“Sorry you failed”);}

Coding guidelines:

A. To avoid confusion, always place the statement or statements of an if or if


– else block inside brackets {}.

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,

Sample code snippet:

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.

The if-else-if statement has the form:

if(boolean_expression1)
statement1;
else
if (boolean_expression2)
statement2;
else
statement3;
For example,

int grade = 68;


if (grade>90){
System.out.println(“Excellent!”);
}
else
if (grade>60){
System.out.println(“Very good!”);
}
else{
System.out.println(“Sorry you failed!”);
{

Example for if –else-if

public class Grade{


public static void main (String [] args){
double grade = 92.0;
if (grade >=90) {
System.out.println(“Excellent!”);
}
else if ((grade < 90) && (grade >=80)) {
System.out.println(“Good Job!”);
}
else if ((grade < 80) && (grade >=60)) {
System.out.println(“Study harder!”);
}
else {
System.out.println(“Sorry, you failed!”);
}
}
}

Common errors when using if – else statements


A. The condition inside the if – else statement does not evaluate to a
boolean value. For example,
//WRONG
int number = 0;
if (number) {
statement
}
The variable number does not hold a Boolean value.
B. Using = instead of == for comparison. For example,
//WRONG
int number = 0;
if (number = 0) {
statement}
//CORRECT
int number = 0;
if (number == 0) {
statement}

C. Writing elseif instead of else if.

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.

In Java we have three types of loops :


A. The while loop
B. The do while loop
C. The for loop

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;

- If the condition is true, the statement is executed; then the condition is


evaluated again
- The statement is executed over and over until the condition becomes
false

int Number = 10;


while ( Number >= 0 ) {
System.out.println( "Number is " + Number );
Number--;
} // end while Number >= 0
System.out.println( "Loop ended");

- The condition to be tested is contained in parentheses (round brackets)


after the word "while", and the body of the loop is in curly braces after the
condition.
- There is no semicolon after the closing curly brace.

The sequence of operations in the loop (after the initialisation of the value of
"Number" to 10, for example) is :

(i) Test whether "Number >= 0".

(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.

Examples of while loops counting from 1 to 10

// 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

The numeric denotations (actual numeric values) appearing in your program


should be exactly the numbers you would talk about in describing what the
program is required to do. In this case, the value 9 should not appear. If you
are converting seconds to minutes and hours, the value 59 should not
appear, only the value 60. The CourseMaster automatic marking system
checks program features such as this.

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 :

public class Test {


static final int REPEATS = 10;
main () {
....
while( Number < REPEATS ) {
....
} // end the loop
} // end main program

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++;
}

Examples of "while" loops

● To add together the sequence 1 + 1/2 + 1/4 + 1/8 + ... until the terms we
are
adding together are smaller than 0.00001

// We need float variables


float Term = 1.0f, Total = 0.0f;
int Counter = 0;
final float DELTA = 0.00001f;
while ( Term > DELTA ) {
// Add the next term to the total
Total += Term;
// Halve the term
Term /= 2.0; // or *= 0.5
// Count them
Counter++;
} // end while Term > 0.00001 loop
System.out.println( "Total " + Total );
System.out.println( "Number" + Counter );

● The value of "Term" is halved each time round the loop; each of these
values is added to the total.

You could use :


Total = Total + Term;
Term = Term / 2.0;
instead of :
Total += Term;
Term /= 2.0;

● 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.

int NextNumber, Biggest = 0;


NextNumber = UserInput.getInt();
while ( NextNumber != 0 ) {
if ( Biggest < NextNumber ) {
Biggest = NextNumber;
}
NextNumber = UserInput.getInt();
} // end while NextNumber non-zero
System.out.println( "Biggest was " + Biggest );

● 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.

- The pattern of execution in this case can be summarized as follows.


loop; test
loop; test; loop; test
loop; test; loop; test; loop; test

- The code in the above programming example could also be written


int Number = 1;
do {
....;
} while ( ++Number <= 10 );

- 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.

Examples of “do” loops

- To read in positive numbers until a zero is encountered, and print the


biggest one.

int NextNumber, Biggest = 0;


do {
NextNumber = UserInput.readInt();
if ( Biggest < NextNumber ) {
Biggest = NextNumber;
}
} while ( NextNumber != 0 );
System.out.println( "Biggest " + Biggest );
Using System.exit()

- 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:

for ( Num = 10; Num > 0; Num-- )


{....;}
for ( Count = 0; Count < 10; Count++ )
{ ....; }

final float DELTA = 0.00001;


float term;
for ( term = 1.0; term > DELTA; term *= 0.5 ) {
....;}

- 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:

for (initialise; test; execute after loop ) {


....;}

- 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.

- The third expression is a statement executed after every execution of the


loop body, before the next test. It typically increments a counter.

- The sequence is now:


init; test;
init; test; loop; incr; test;
init; test; loop; incr; test; loop; incr; test;

- 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.

"for" loops – Readability

- 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.

- The "for" loop could be written as a "while" loop in the form:


declaration;
initialise;
....
while ( test ) {
....;
incr;
}
- In this layout, the loop control is not so clearly seen.

Defaults

- Defaults are obvious;


- any or all of the three control statements can be omitted. The construct
for ( ; ; ) {
....;}
- gives no initialization, assumes a TRUE test result, and performs no
incrementing.
- You may find the comma "operator" useful in the initialization and
increment parts of the loop control.

for (
this = 10, that = 0;
this > that;
this--, that++
){
....;}

General points on loops - Nesting of loops

- Loops may, of course, be nested to any depth in any combination as


required.

for ( int year = 1900; year < 2000; year++ ) {


for ( int month = 0; month < 12; month++ ) {
....;
// execute 1200 times ...
} // end month loop for each year
} // end year loop

- 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.

The "break" statement

- 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 ...");

- The program continues after the end of the loop.


- Within a nested loop, "break" causes the inner most loop to be
abandoned.

The "continue" statement

- 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.

Example of "break" and "continue"

- 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

Comments: It is good practice to comment the end closing curly brace of


any loop which extends over more than a few lines. The
CourseMaster system expects a comment after every closing brace which
appears more than 10 lines from its opening curly brace.

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.

Sum, minimum, and maximum of data

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

- To sum the square of all the integer values from 1 squared up to 99


squared.

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

- To read characters until a full stop (period) is encountered, and to count


the number of occurrences of the letter "e", you could write:

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");

Increasing and decreasing integers

- 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

You might also like