- /**
- * LoopExamples
- *
- * @author T K Rogers
- * @version 01-04-06
- */
- public class LoopExamples {
- public static void
main( ) {
-
double output = 0;
-
int x;
-
double array [ ] = { 20.0, 2.0, 3.0 };
-
- // The output for
each of the following loops is the same
- //for
loop example
- for ( x = 0; x <
3; x++) { // initializes; tests; increments
-
output += array [x];
-
System.out.print ( array [x] + ", " );
- }
-
System.out.println ("____for loop: output = " + output + "\n");
- output = 0;
-
-
//while loop example
- x = 0;
// initializes
- while ( x < 3 )
{
// tests
-
output += array [x];
-
System.out.print ( array [x] + ", " );
-
x++;
// increments
- }
-
System.out.println ( "____while loop: output = " + output + "\n" );
- output = 0;
-
-
// do...while loop example
- x = 0;
// initializes
- do {
-
output += array [x];
-
System.out.print ( array [x] + ", " );
-
x++;
// increments
- } while (x
< 3);
// tests
-
System.out.println ( "____do...while loop: output = " + output + "\n" );
- output = 0;
-
-
// foreach loop example
- for ( double i:
array ) { // Automatically initializes, increments
by 1, and
-
// runs until reaching the end of the
list
-
output += i; // The variable i now takes the place
of each value in a list
-
// starting with the first and progressing to the last
one in
-
// sequential order
-
System.out.print ( i + ", " );
- }
-
System.out.println ( "____foreach loop: output = " + output + "\n" );
- output = 0;
- }
-
- }