Professional Documents
Culture Documents
FSDLecture 5
FSDLecture 5
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
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.
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
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.
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
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.
}}
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.
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 :
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
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("
\"Alone at last.\"");
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
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.
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
...
}
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);
}
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
}
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 )
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.
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.
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
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.
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
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?
Reading in a loop
What should the loop look like?
read score
while (not end of file) {
process score
read score
}
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
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 :
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
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
Reading in a loop
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);
}
}
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 :
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;
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
= 5 cents
Next Lesson
Introduction to collections of data and associated
operations:
Array basics
Simple Array processing Loops
One-Dimensional Arrays
Examples of Array Programs