<< Chapter < Page | Chapter >> Page > |
Exercise Write equivalent programs using a while loop and a do-while loop.
Concept Although all loop structures can be programmed as
while
loops,
one special case is directly supported: writing a loop that executes a predetermined numberof times. The
for
statement has three parts:
for (int i = 0; i<N; i++)
The first part declares a loop control variable and gives it an initial value.
The second part contains the exit condition: the loop body will be executedas long as the expression evaluates to true. The third part describes how
the value of the control variable is modified after executing the loop body.The syntax show is the conventional one for executing a loop
N
times.
Program: Control06.java
// Learning Object Control06
// counting with for statementspublic class Control06 {
static final int N = 6; public static void main(/*String[] args*/) { int factorial = 1;
for (int i = 0; i < N; i++)
factorial = factorial * (i+1); System.out.println(factorial);
}}
This program computes the first six factorials in a
for
loop
and the last value is printed.
N
and the variable
factorial
are allocated and initialized.i
is allocated and initialized.i<N
is evaluated and evaluates to true.Jeliot displays
Entering the for loop
.for
statement.Continuing the for loop
as long as the expression evaluates to true, and
Exiting the for loop
when
it evaluates to false.factorial
is printed.
Exercise Rewrite the program using a
while
loop.
Concept Arbitrary expressions can be given for the initial value of the
for
statement, the exit condition, and the modification of the control variable.
Program: Control07.java
// Learning Object Control07
// General for statementspublic class Control07 {
static final int N = 100; public static void main(/*String[] args*/) { int sum = 0;
for (int i = 0; i < Math.sqrt(N); i = i + 3)
sum = sum + i; System.out.println(sum);
}}
This program computes the sum of multiples of three that are less
than the square root of
N
.
N
and the variable
sum
are allocated and initialized.i
is allocated and initialized.i<Math.sqrt(N)
is evaluated and evaluates to true.
Jeliot displays
Entering the for loop
.for
statement.Continuing the for loop
as long as the expression evaluates to true, and
Exiting the for loop
when
it evaluates to false.sum
is printed.Notification Switch
Would you like to follow the 'Learning objects for java (with jeliot)' conversation and receive update notifications?