JMU
Repetition and Looping
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Commonalities Across these Situations
Definitions
Important Concepts
Important Concepts (cont.)
while Loops
while Loops (cont.)

An Example

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.)
http://www.smbc-comics.com/comics/20120628.gif
(Courtesy of Saturday Morning Breakfast Cereal)
do-while Loops
do-while Loops (cont.)

An Example

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 Loops
for Loops (cont.)

An Example

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.)
Loops and Scope
Loops and Updating
Java vs. Python - Important Differences
Java vs. Python - Important Differences