while loop, which has
the form while (test) statement
while loop
called the do loop, and has the form do statement while (test).
for loop,
which has the form
for (initialization; test; increment) statement;
initialization;
while (test) {
statement;
increment;
}
for
loop of Pascal.
for loop can be ommitted
(in which case it is ignored).
int i; // A counter variable
int factorial; // The factorial of N
factorial = 1;
for (i = 1; i <= N; i = i+1) {
factorial = factorial * i;
}
var++.
++ can be used before or after any variable
(or reference to a memory location). The effect is to increment
the variable by one (or an equivalent of one).
-- can be used to decrement the variable by
one.
++ and -- with integer
variables (and their variants).
++ comes before the variable, the value of the
expression is the new value of the variable.
++ comes after the variable, the value of the
expression is the old value of the variable.
Write a program that builds a 10x10 multiplication table. If you have time, you may wish to extend it to read the width and height from the command line.
The core of your program will most likely look something like the following
for(row = 1; row <= width; ++row) {
// You may want to fill in something here
for(column = 1; column <= width; column = column + 1) {
// Fill in something here
} // for each column
// You may want to fill in something here
} // for each row
break exits the current loop (or switch).
continue exits the current repetition of the loop
(going back to the test, and, possibly, to another repetition of
the loop).
label: statement and then use
break label to break out of that statement.
For example
outer:
for (i = 0; i < N; ++i) {
inner:
for (j= 0; j < M; ++j) {
if (meetsCondition(i,j)) {
System.out.println(
"Found what we were looking for at (" +
i + "," + j + ")"
);
break outer;
} // if
} // inner for loop
// Here's where you go if you break out of the inner loop
} // outer for loop
// Here's where you go if you break out of the outer loop
continue can take a label, and returns to the
next iteration of the labeled loop.
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Tue Oct 7 17:12:18 1997.
This page generated on Wed Nov 5 12:38:45 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu