<< Chapter < Page | Chapter >> Page > |
Exercise According to a formula by Euler,
Write a program to compute the series until the difference between the two terms is less than 0.1.
Concept A loop enables the execution of a statement (including a block of statements within braces) an arbitrary number of times.This statement is called the loop body . In a do-while loop, an expression is evaluated after each execution of the loop body, andthe loop body continues to execute if and only if the expression evaluates to true.
The loop body of a do-while loop will execute at least one time. This type of statement is particularly appropriate for processing input,because you need to input data at least once before you can test it in an expression.
Program: Control04.java
// Learning Object Control04
// do-while loopspublic class Control04 {
public static void main(/*String[] args*/) {
int input; do {
input = Input.nextInt(); } while (input <= 0);
System.out.println(input); }
}
The program reads interactive input until a positive number is entered.
input
is allocated but not initialized.Entering the do-while loop
.input
.
First, enter a negative integer.while
is evaluated.
Since it evaluates to true, the loop body is executed again.Jeliot displays
Continuing the do-while loop
.input
.while
is evaluated.
Since it evaluates to false, the execution of the do-while loop is completed.Jeliot displays
Exiting the do-while loop
.Exercise Rewrite this program with a while loop. Compare it to the do-while loop.
Concept The exit from a while loop occurs
before the loop body and
the exit from a do-while loop occurs
after the loop body.
The
break
statement can
be used to exit from an arbitrary location or locations from within the loop body.
The
break
statement is useful when the expression that leads to exiting the loop cannot
be evaluated until some statements from the loop body have been executed,and yet there remain statements to be executed after the expression is evaluated.
Program: Control05.java
// Learning Object Control05
// break statementspublic class Control05 {
public static void main(/*String[] args*/) {
int input; int sum = 0;
while (true) { input = Input.nextInt();
if (input < 0) break;
sum = sum + input; }
System.out.println(sum); }
}
The program sums a sequence of nonnegative integers read from the input and terminates when a negative value is read.
sum
is initialized with the value zero.while
statement is executed with
true
as the loop expression.
Of course,
true
will never evaluate to false, so the loop will never be exited
at the
while
.break
statement
is executed and Jeliot displays
Exiting the while loop because of the break
.Continuing without branching
.Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?