You are on page 1of 37

Fundamentals of Software

Development
CT010-3-1
Structured Programming Control
Structures in Java

Prepared by: JRK First Prepared on:27 th July 2005 Last Modified on:14th December 2005
Quality checked by: GTK
Copyright 2005 Asia Pacific University College of Technology and Innovation

Topic & Structure of the lesson


Structured Programming Control Structures
Looping constructs
while loop
do..while loop
for loop

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Learning Outcomes
At the end of this topic, you should be able to:
Create, edit, compile, run and debug simple proceduralbased Java programs using iterative constructs.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Key Terms
If you have mastered this topic, you should
be able to use the following terms correctly
in your assignments and exams:
initialization
termination
increment

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Generally speaking, a while statement performs some
action while a certain condition remains true. The
general syntax of the while statement is:
while (condition)
statements
That is, while condition is true, do statement.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
If more than 1 statements to be executed :
while (condition) {
statement-1;
statement-2;
}
If were careless in writing the loop and the condition
never becomes false, the loop will continue to execute
forever - an infinite loop.
CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Here is an expanded program from the previous
Temperature program. When executed, produces the
table of equivalent Centigrade and Fahrenheit.
class Temperature {
public static void main (String[] args) {
final double
LOW_TEMP = -10.0,
HIGH_TEMP = 10.0;
double cent, // The Centigrade temperature.
fahr; // The Fahrenheit temperature.

}}

System.out.println("DEGREES C\tDEGREES F");


cent = LOW_TEMP;
while (cent <= HIGH_TEMP) {
fahr = (9.0/5.0) * cent + 32.0;
// Convert C to F
System.out.println("\t" + cent + "\t\t" + fahr);
cent = cent + 1.0; // Increment the Centigrade value.
}

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Example 2
Suppose we want the computer to print :
10 in a bed and the little one said,
Roll over, roll over.
They all rolled over and one fell out,
9 in a bed and the little one said,
Roll over, roll over.
They all rolled over and one fell out,
8 in a bed and the little one said,
:
1 in a bed and the little one said,
Alone at last.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Example 2
The 1st thing to do is to decide :
1. which pieces of the song are to be
printed just once and
2. which pieces will be repeated.
==> the pieces to be printed once will go
either before or after the loop;
==> the ones that are repeated can be put
inside the loop.
We organize our program schematically as :

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Example 2
We organize our program schematically as :
print first line of verse
while (more verses) {
print rest of verse
print first line of next verse
}
print first line of next verse

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

while statement
Example 2 : Sample Program
class TenInABed {
static final int
MAX_NUMBER_IN_BED = 10;
public static void main (String[] args) {
int numberInBed;
System.out.println(MAX_NUMBER_IN_BED
+ " in a bed and the little one said,");
numberInBed = MAX_NUMBER_IN_BED - 1;
while (numberInBed > 0) {
System.out.println(" \"Roll over, roll over.\"");
System.out.println("They all rolled over and one fell out,");
System.out.println(numberInBed + " in a bed and the little one said,");
numberInBed = numberInBed - 1;
}

System.out.println("

CT010-3-1 Fundamentals of Software Development

\"Alone at last.\"");

Structured Programming Control Structures in Java

for statement
Use the for loop when you know the constraints of the
loop (its initialization instruction, termination criteria,
and increment instruction). The general form of the for
statement can be expressed like this:
for (initialization; termination; increment)
statements

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

for statement
initialization ==> a statement that initializes the
loop--its executed once at the beginning of the loop.
termination ==> expression that determines when to
terminate the loop. This expression is evaluated at the
top of each iteration of the loop. When the expression
evaluates to false, the for loop terminates.
increment ==> expression that gets invoked for each
iteration through the loop.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

for statement
For instance, for loops are often used to iterate over the
elements in an array, or the characters
in a string.
// a is an array of some kind
...
int i;
int length = a.length;
for (i = 0; i < length; i++) {
...
// do something to the i th element of a
...
}

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

for statement
Example 1
Lets review at the Temperature program. :
while (cent <= HIGH_TEMP) {
fahr = (9.0/5.0) * cent + 32.0; // Convert C to F
System.out.println("\t" + cent + "\t\t" + fahr);
}

cent = cent + 1.0; // Increment the Centigrade value.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

for statement
Example 1
Using a for statement, our temperature table loop can
be rewritten as
for (cent = LOW_TEMP; cent <= HIGH_TEMP; cent =cent+1.0 ) {
fahr = (9.0/5.0) * cent + 32.0; // Convert C to F
}

System.out.println("\t" + cent + "\t\t" + fahr);

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

for statement
Example 1 : Sample Program
class Temperature {
public static void main (String[] args) {
final double
LOW_TEMP = -10.0,
HIGH_TEMP = 10.0;
double
cent, // The Centigrade temperature.
fahr; // The Fahrenheit temperature.
System.out.println("DEGREES C\tDEGREES F");
cent = LOW_TEMP;
for (cent = HIGH_TEMP; cent <= HIGH_TEMP; cent =cent+1.0 )

fahr = (9.0/5.0) * cent + 32.0; // Convert C to F


System.out.println("\t" + cent + "\t\t" + fahr);

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

do while statement
Java provides another loop, the do-while loop, which
is similar to the while loop :
do {
statements
} while (condition);
do-while Vs while : The main difference between
these two is that in do-while loop the expression is
evaluated at the bottom of the loop, thus, the body of
the loop is always executed AT LEAST ONCE.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

do while statement
The do-while statement is a less commonly used
loop construct in programming but does have its
uses. For example, the do-while is convenient to use
when the statements within the loop must be
executed at least once.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

do while statement
Example 1
When reading information from a file, you
know that you will always have to read at least
one character. Therefore, the do-while loop
will be appropriate to be used in this case :
int c;
Reader in;
...
do {
c = in.read();
...
} while (c != -1);
CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


Write and run a program that prints the average of 5
random double value. Your output should look like
this :
Average = 0.533764716823967
(hint : use the method Math.random() )

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Quick Review Question


Sample answer
public class averageRandom {
public static void main(String[] args) {
double randNo, sum=0.0;
for(int i=0; i<5; i++) {
randNo = Math.random();
sum = sum + randNo;
System.out.println(randNo+"");
}
System.out.println(average = +
sum/5);
}
}
CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
Write a program to read test scores and compute the
minimum, maximum and average scores. Imagine
someone at a computer entering a sequence of
scores; after entering the scores, the person
signals the end of the data by entering a special
character that indicates the end of file (eof). This
character, which varies from computer to computer,
is commonly a control-d or control-z.

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
Sample Output
Enter score (eof ends the data) : 85
Enter score (eof ends the data) : 62
Enter score (eof ends the data) : 93
Enter score (eof ends the data) : 87
Enter score (eof ends the data) : 51
Enter score (eof ends the data) : ^D or ^Z
5 scores were entered.The average score was 75.6
The maximum score was 93
The minumum score was 51

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
Questions ??????
How do we calculate the average?
The maximum?
The minimum?
But before these answering these questions :
What should the loop look like?
How do we test for end of file?

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
What should the loop look like?
read score
while (not end of file) {
process score
read score
}

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
Questions ??????
How do we test for end of file?
Use Keyboard.eof() as a true/false value.
Keyboard.eof() is true when Keyboard.readInt() /
Keyboard.readDouble() encountered the end of file.
Keyboard.eof() is false when Keyboard.readInt() /
Keyboard.readDouble() did not encounter the end of
file

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
So, now we have :
read score
while (!Keyboard.eof()) {
process score
read score
}
Now, lets add in the read score & process score
section :

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
int score, sumOfScores=0; numberOfScores=0;
System.out.print(Enter score (eof ends the data): );
score = Keyboard.readInt();
while (!Keyboard.eof()) {
numberOfScores++;
sumOfScores = sumOfScores + score;

// new score
// update sum

System.out.print(Enter score (eof ends of data): );


score = Keyboard.readInt();

How about calculating the average & determining


the maximum & minimum score???
CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
class Scores {
// Author: Arthur L. Reingold, October 31, 1994.
public static void main (String[] args) {
int score, sumOfScores = 0, numberOfScores = 0;
System.out.print("Enter score (eof ends the data): ");
score=Keyboard.readInt();
int maxOfScores = score;
int minOfScores = score;
while (!Keyboard.eof()) {
numberOfScores++;
// new score
sumOfScores = sumOfScores + score; // update sum
contd.
CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop

if (maxOfScores < score)


// new largest score
maxOfScores = score;
if (minOfScores > score)
// new smallest score
minOfScores = score;
System.out.print("Enter score (eof ends the data): ");
score=Keyboard.readInt();
}

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Reading in a loop
// Printing out the result
if (numberOfScores == 0)
System.out.println("No scores were entered.");
else if (numberOfScores == 1)
System.out.println("Only one score was entered. It was "
+ sumOfScores);
else {
System.out.println(\n\n +numberOfScores + " scores were
entered.");
System.out.println("The average score was "
+ ((double)sumOfScores)/numberOfScores);
System.out.println("The maximum score was "
+ maxOfScores);
System.out.println("The minimum score was "
+ minOfScores);
}
}

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

break statement
As in switch statements, the break statement can
also be used terminate the execution of the
iteration statements while and for.
The use of a break in loops can simplify writing
code in what is sometimes called the loop-and-ahalf problem. For example :

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

break statement
read score
while (!Keyboard.eof()) {
process score
read score
}

while (true) {
read score
if (Keyboard.eof())
process score
}
CT010-3-1 Fundamentals of Software Development

break;

Structured Programming Control Structures in Java

Follow Up Assignment
Write an application that accepts a sequence of
inputs that describe the quantities and types of
coins held by a person. The application should
then process the inputs and display the total value
of these coins.
Note:
Half-dollar = 50 cents
Quarter

= 25 cents

Dime

= 10 cents

Nickel

CT010-3-1 Fundamentals of Software Development

= 5 cents

Structured Programming Control Structures in Java

Summary of Main Teaching Points


Structured Programming Control Structures
Looping constructs
while loop
do..while loop
for loop

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

Next Lesson
Introduction to collections of data and associated
operations:
Array basics
Simple Array processing Loops
One-Dimensional Arrays
Examples of Array Programs

CT010-3-1 Fundamentals of Software Development

Structured Programming Control Structures in Java

You might also like