final int LIMIT = 100; // setup
int count = 1; // - initialize the loop control variable
int sum = 0; // - and the summing variable
while (count <= LIMIT) // loop control 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.
The loop would print and sum the numbers from _____________ to _____________.
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.
String keepGoing = "Y";
int nextVal;
while (keepGoing.equals("y") || keepGoing.equals("Y"))
{
System.out.print("Enter the next integer: "); //do work
nextVal = scan.nextInt();
if (nextVal % 37 == 0)
{
System.out.println (nextVal + " is divisible by 37.");
}
else
{
System.out.println (nextVal + " is NOT divisible by 37.");
}
System.out.print("Type y or Y to keep going: "); //update condition
keepGoing = scan.next();
}
System.out.println("Bye, hope this program was helpful!");
Not all counters are counting the number of times a loop
executes. Modify this loop so that it counts the
integers that are divisible by 37 and those that are not. Write your
changes on the code above as follows:
while (______________________________________________________________________)
{
..... // Same code as before
System.out.print("Type n or N to stop: "); //update condition
keepGoing = scan.next();
}
count = 10;
while (count >= 0)
{
System.out.println(count);
count = count + 1;
}