final int LIMIT = 100; // setup
int count = 1; // - initialize the loop control variable
int sum = 0; // - and the summing variable
while (count <= LIMIT) // condition
{ // body
System.out.println(count); // -- perform task
sum = sum + count; // (print and sum)
count = count + 1; // -- update condition
}
System.out.println ("The sum of the integers from 1 to " +
LIMIT + " is " + sum);
This loop is an example of a count-controlled loop, that is, a loop that contains a counter (a variable that increases or decreases by a fixed value -- usually 1 -- each time through the loop) and that stops when the counter reaches a certain value. Not all loops with counters are count-controlled; consider the example below, which determines how many even numbers must be added together, starting at 2, to reach or exceed a given limit.
final int LIMIT = 16; TRACE
int count = 1; sum nextVal count
int sum = 0; --- ------- -----
int nextVal = 2;
while (sum < LIMIT)
{
sum = sum + nextVal;
nextVal = nextVal + 2;
count = count + 1;
}
System.out.println("Had to add together " + (count-1) + " even numbers " +
"to reach value " + LIMIT + ". Sum is " + sum);
Note that although this loop counts how many times the body is executed,
the condition does not depend on the value of count.
Not all loops have counters. For example, if the task in the loop above were simply to add together even numbers until the sum reached a certain limit and then print the sum (as opposed to printing the number of things added together), there would be no need for the counter. Similarly, the loop below sums integers input by the user and prints the sum; it contains no counter.
int sum = 0; //setup
String keepGoing = "Y";
int nextVal;
while (keepGoing.equals("y") || keepGoing.equals("Y")
{
System.out.print("Enter the next integer: "); //do work
nextVal = scan.nextInt();
sum = sum + nextVal;
System.out.println("Type y or Y to keep going"); //update condition
keepGoing = scan.next();
}
System.out.println("The sum of your integers is " + sum);
Exercises
count = 10;
while (count >= 0)
{
System.out.println(count);
count = count + 1;
}