Java Control Structures II
Why Is Repetition Needed?
There
are many situations in which it is necessary to repeat a set of
statements. For example, when a certain formula is going to be used
several times (obtaining an average of grades for students in a class).
Java has three repetition, or looping, structures that let you repeat
statements over and over again until certain conditions are met: while,
for, and do…while.
while Looping (Repetition) Structure
The
reserved word while can be used to repeat a set of statement until a
certain condition is met. The syntax for the while loop is:
while (expression)
statement
The
expression, called a loop condition, acts as a decision-maker and is a
logical expression. The statement is called the body of the loop.
Moreover, the statement can be either a simple or compound statement.
The
expression provides an entry condition. If it initially evaluates to
true, the statement executes. The loop condition—the expression—is then
reevaluated. If it again evaluates to true, the statement executes
again. The statement (body of the loop) continues to execute until the
expression is no longer true.
A loop that continues to execute endlessly is called an infinite loop.
A
variable in the loop condition that is used to determine whether the
body of the loop will execute is called a loop control variable.
Counter-Controlled while Loops
When
you know exactly how many times certain statements need to be executed,
the while loop assumes the form of a counter-controlled while loop. To
do this, you set up a counter that is initialized to 0 before the while
statement and then increment the counter in the while statement to keep
track of how many times the body has been executed. The syntax for a
counter-controlled while loop is:
int N = some value either inputted by the user, or some specified value;
int counter = 0;
while (counter < N)
{
statements
counter++;
}
Sentinel-Controlled while Loops
You
might not know exactly how many times a set of statements needs to be
executed, but you do know that the statements need to be executed until a
special value is met. This special value is called a sentinel.
In
such cases, you read the first item before entering the while
statement. If this item does not equal the sentinel, the body of the
while statement executes. The while loop continues to execute as long as
the program has not read the sentinel. Such a while loop is called a
sentinel-controlled while loop. The syntax for the sentinel-controlled
while loop is:
input first data item into variable;
while (variable != sentinel)
{
.
.
.
input a data item into variable;
}
Flag-Controlled while Loops
Using
a boolean value to control a while loop (called a flag variable) is
called the flag-controlled while loop. The syntax for this loop can be
similar to the following:
boolean found = false;
while(!found)
{
.
.
if(expression)
found = true;
.
.
}
EOF-Controlled while Loops
If
the data file is frequently altered (for example, if data is frequently
added or deleted), it’s best not to read the data with a sentinel
value. Someone might accidentally erase the sentinel value or add data
past the sentinel. Also, the programmer sometimes does not know what the
sentinel is. In such situations, you can use an EOF (End Of
File)-controlled while loop.
In
Java, the form of the EOF-controlled while loop depends on the type of
stream object used to input data into a program. It now follows that a
general form of the EOF-controlled while loop that uses the Scanner
object console to input data is of the following form:
while (console.hasNext())
{
// Get the next input (token) and store it in an appropriate variable.
// Process the data.
}
If the input source is a file, the condition might be something like infile.hasNext(), rather than console.hasNext().
Teaching Tip
In
the Windows console environment, the end-of-file marker is entered
using Ctrl+z. (Hold the Ctrl key and press z.) In the UNIX environment,
the end-of-file marker is entered using Ctrl+d. (Hold the Ctrl key and
press d.)
More on Expressions in while Statements
There
are situations where the expression in the while statement may be
controlled by multiple variables. In such cases, relational operators
are often used to create more complex logical conditions.
Programming Example: Checking Account Balance
This
program calculates a customer’s checking account balance at the end of
the month. The input to this program is a file consisting of the
customer’s account number, account balance at the beginning of the
month, and each transaction (type and amount) made by the customer. The
transactions can be withdrawals (subtracted from balance), interest
(added to balance), and deposits (added to balance). The data is in a
specific format.
The
output consists of the account number, beginning balance, ending
balance, total interest paid, total amount deposited and number of
deposits made, total amount withdrawn and number of withdrawals made.
The output must also be in the specified format.
The
solution to this example consists of declaring and initializing
variables and objects. A Scanner object and Filereader object are used
to read in data from the file based on the format. Once the transaction
codes are read in, a switch statement is used to determine what the
code does and whether the amount it is associated with should be added
or subtracted from the balance. An EOF-controlled while loop is used to
make sure all the data is read in and put through the switch statement.
Finally, the output is printed to a file using a PrintWriter object.
Programming Example: Fibonacci Number
A Fibonacci number, part of a Fibonacci sequence:
1, 1, 2, 3, 5, 8, 13, 21, 34, …
can be found using the following formula:
an = an-1 + an-2
This program determines the nth Fibonacci number given the first two.
The input to this program is first two Fibonacci numbers and the position in the sequence of the desired Fibonacci number (n).
The output to this program is the nth Fibonacci number.
The
solution consists of prompting the user to enter Fibonacci number 1,
Fibonacci number 2, and the n, so that Fibonacci number n can be
calculated. The first Fibonacci number is stored in the variable
previous1, the second Fibonacci number is stored in the variable
previous2, and the n is stored in the variable nth Fibonacci.
If…else
statements are used to check if the first or second Fibonacci number is
the desired number, if it isn’t the following while loop is entered to
determine the number in the nth position:
counter = 3; //you already know the first and second number so you are starting with the third
while(counter <= nthFibonacci)
{
current = previous2 + previous1;
previous1 = previous2;
previous2 = current;
counter++;
}
The final answer will be stored in current.
The for Looping (Repetition) Structure
The
Java for looping structure is a specialized form of the while loop. Its
primary purpose is to simplify the writing of counter-controlled loops.
For this reason, the for loop is typically called a counted or indexed
for loop.
The general form of the for statement is:
for (initial statement; loop condition; update statement)
statement
The initial statement, loop condition, and update statement are called for loop control statements.
The for loop executes as follows:
1. The initial statement executes
2. The loop condition is evaluated. If the loop condition evaluates to true:
a. Execute the for loop statement.
b. Execute the update statement.
3. Repeat Step 2 until the loop condition evaluates to false.
The initial statement usually initializes a variable (called the for loop control, or indexed variable).
Some additional comments on for loops follow:
If the loop condition is initially false, the loop body does not execute.
The
update expression, when executed, changes the value of the loop control
variable (initialized by the initial expression), which eventually sets
the value of the loop condition to false. The for loop executes
indefinitely if the loop condition is always true.
If you put a semicolon at the end of a for statement (just before the body of the loop), the action of the for loop is empty.
In a for statement, if the loop condition is omitted, it is assumed to be true.
In
a for statement, you can omit all three statements—initial statement,
loop condition, and update statement. The following is a legal for loop:
for (;;)
System.out.println("Hello");
This is an infinite for loop, continuously printing the world Hello.
Programming Example: Classify Numbers
This program reads a given set of integers and prints the number of odd and even integers, as well as the number of zeros.
The input to this program is 20 integers (positive, negative, and zeros) but the number of integers read can be easily modified.
The output is the number of zeros, even numbers, and odd numbers.
The
solution consists of using a for loop to get and evaluate 20 numbers
from the user. Each number is put through a switch structure with cases
depending on the remainder if the number is divided by 2. If the
number is even the number of evens is incremented, if the number is 0,
the number of zeros is incremented, and if the number is odd count is
incremented.
The do…while Looping (Repetition) Structure
The
third type of looping or repetition structure uses the reserved words
do and while, and is called the do…while loop. The syntax of this loop
is:
do{
statement(s);
}
while(expression);
The expression is called the loop condition.
The
statement executes first, and then the expression is evaluated. If the
expression evaluates to true, the statement executes again. As long as
the expression in a do...while statement is true, the statement
executes. To avoid an infinite loop, you must make sure that the body of
the loop contains a statement that ultimately makes the expression
evaluate to false and assures that it exits properly.
In
a while or for loop, the loop condition is evaluated before executing
the body of the loop. Therefore, while and for loops are called pre-test
loops. On the other hand, the loop condition in a do...while loop is
evaluated after executing the body of the loop. Therefore, do...while
loops are called post-test loops.
break and continue Statements
The
break and continue statements alter the flow of control in a program.
The break statement is typically used for two purposes:
1. To exit early from a loop
2. To skip the remainder of a switch structure
After the break statement executes, the program continues to execute with the first statement after the structure.
The
break statement can be placed within an if statement in the loop. If
the certain condition is found, the loop will be exited immediately.
This is similar to changing the value of a flag variable in an if
statement within a flag-controlled loop.
The
continue statement is used in while, for, and do...while structures.
When the continue statement is executed in a loop, it skips the
remaining statements in the loop and proceeds with the next iteration of
the loop. In a while and do...while structure, the expression (that is,
the loop-continue test) is evaluated immediately after the continue
statement. In a for structure, the update statement is executed after
the continue statement, and then the loop condition (that is, the
loop-continue test) executes.
Teaching Tip
The continue statement cannot be used in a switch statement.
Teaching Tip
In
a while loop, when the continue statement is executed, if the update
statement appears after the continue statement, the update statement is
not executed. In a for loop, the update statement always executes.
Teaching Tip
Java also supports labeled break and labeled continue statements. For more information, see:
http://www.dickbaldwin.com/java/Java026.htm#thebreakandcontinuestatements
Nested Control Structures
Nesting
of control structures provides new power, subtlety, and complexity. if,
if…else, and switch structures can be places within while loops. For
loops can be found within other for loops as in the following example:
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= I; j++)
System.out.print(“*”);
System.out.println();
}
Analysis
of this program will show how the outer loops provides the limiting
condition for the inner loop which controls the number of stars printed
during each iteration.
The final output of this program is:
*
**
***
****
*****
Walang komento:
Mag-post ng isang Komento