Java Reference

In-Depth Information

Java syntax: for-loop for processing a range of integers
b..c

for
(
int
i= b; i <= c; i= i + 1) {

Process
i;

}

Purpose
: To perform the sequence of statements “Process
b
; Process
b+1
;

...; Process
c
;”. Here, “Process
i
” can be any statement sequence that

refers to variable
i
. Also,
b
and
c
can be any integer expressions such that

b<=c+1
. If
b
=
c+1
, then no integers are processed.

the following sequence, the second declaration is illegal, since variable
b
is

declared in the first line. But the third line, the assignment to
b
, is legal.

//
A legal initializing declaration

int
b= 45;

//
An illegal declaration, since b is already declared

int
b= 61;

//
A legal assignment

b= b + 2;

2.3.8

Processing a range of integers

This section need not be read at this time. It is presented here so that instructors

who want to introduce loops early can do so. If you are not interested in study-

ing loops at this point, skip this section.

At times, we want to write a program segment to process a range of integers.

Here are some examples of tasks that we might want to perform:

• Add the squares of the integers in the range
1..100
(i.e. the integers
1
,
2
,

…,
100
).

• Determine whether some integer in the range
2..n
divides an integer
k
.

• Find the first integer in the range
100..
(i.e. the first integer
≥ 100
) that is

a power of
2
(i.e. can be written in the form
2
k
for some
k
).

• Find the number of times the letter
'e'
appears in
String s
(this requires

processing the possible indices
1..(s.length-1)
of
s
).

Program segments to process a range of integers are usually written using a

loop
, and often with what is called a
for-loop
. Chapter 7 covers loops in detail;

here, we provide just enough information to allow you to write simple loops to

process a range of integers.

Suppose you want to implement the following sequence of statements,

which stores in
int
variable
x
the sum of the integers in the range
2..200
. Here

is one way to do it:

Search WWH ::

Custom Search