Repetition and Looping
An Introduction with Examples in Java |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
while
Loopswhile
Loops (cont.)
speedInKnots = 1.; while (speedInKnots < 50.) { feetPerHour = speedInKnots * feetPerKnot; speedInMPH = feetPerHour / feetPerMile; System.out.printf("knots: %5.2f\tmph: %5.2f\n", speedInKnots, speedInMPH); speedInKnots = speedInKnots + 1.; }
while
Loops (cont.)while
Loops (cont.)do-while
Loopsdo-while
Loops (cont.)
speedInKnots = 1.; do { feetPerHour = speedInKnots * feetPerKnot; speedInMPH = feetPerHour / feetPerMile; System.out.printf("knots: %5.2f\tmph: %5.2f\n", speedInKnots, speedInMPH); speedInKnots = speedInKnots + 1.; } while (speedInKnots < 50.);
do-while
Loops (cont.)for
Loopsfor
Loops (cont.)
for (speedInKnots=0.; speedInKnots < 50.; speedInKnots=speedInKnots+1.) { feetPerHour = speedInKnots * feetPerKnot; speedInMPH = feetPerHour / feetPerMile; System.out.printf("knots: %5.2f\tmph: %5.2f\n", speedInKnots, speedInMPH); }
for
Loops (cont.)for
Loops (cont.)for
loopsfor (int i=0; i<args.length; i++) { System.out.printf("Argument %d is: %s\n", i, args[i]); }
for (j=0; j<50; ++j)
for (int i=0; i<50; ++i)
i
and j
j
can be accessed outside of the
loop, i
can'tage = age + 1;
)age += 1;
)for
loop can be provided a
range of integers using the range()
functionfor
loop can be provided a
list/array/stringdo
loop