for loops
while loops
do-while loops
Computers don't complain when we ask them to do the same thing over and over again. For example, suppose I'm feeling low and I want to program my computer to say "You are great!" 100 times. I could write the 100 lines of code:
outBox.printLine("You are great!");
outBox.printLine("You are great!");
outBox.printLine("You are great!");
...
outBox.printLine("You are great!");
and the computer would be happy to run this program. Unfortunately, programmers will not be that happy about repeatedly having to type in the same line 100 times (and making sure there are exactly 100 lines and not, say, 99 or 101 times). Besides, the code is a bit unwieldy and hard to read (what if it was a 10000 and not 100 !)
Since this kind of repetitous behavior occurs so often in programming, we have special instructions for making this simple. It is called a for-loop.
Syntax for a for-loop is
for (<initialization> ; <boolean expression> ; <increment>)
<java statement> // this is the body of the for-loop
Example 1:
for (int i=1; i <= 100 ; i++)
outBox.printLine("You are great!");
This for-loop works as follows:
Here,
We can also think of "unwinding" the loop:
Value of loop:variable i | loop condition:i <= 100 | result of instruction |
1 | true | "You are great!" is printed |
2 | true | "You are great!" is printed |
3 | true | "You are great!" is printed |
... | ||
101 | false | instruction not executed |
What do the following do? Try unwinding the loop.
Example 2:
for (int i=-4; i<4 ; i += 2)
outBox.printLine("You are great!");
Example 3:
for (int i=-4; i<4 ; i += 2)
outBox.printLine("line " + i);
Example 4: How would you compute the factorial of n?
int fact = 1;
int n = inBox("Enter a positive integer:");
for (int k=2; k<=n ; k++)
fact = fact*k;
outBox.printLine("The factorial of "+n+" is "+fact);
Practice: Write a for-loop that
If you are not careful, a for-loop may loop forever-
What does this do?
for (int i=1; i<100 ; i--)
outBox.printLine("line " + i);
Sometimes you want the loop to go on forever. For example if you are animating a ball that bounces back and forth in a window of width 200:
int x=50, y = 100, width = 200, increment = 1;
for (;;) { // forever loop
eraseBall(x,y); // erase ball on screen
x += increment; // update position of ball
drawBall(x,y); // redraw ball in new position
if (x ==width || x == 1) // ball is at boundary so
increment = increment*(-1); // switch directions
}
A while loop is the most general type of loop you can use. For-loops are special cases of while-loops: Any for-loop can be written as a while-loop but not vice versa.
while (<conditional expression>)
<java statement> // body of while-loop
or
while (<conditional expression>)
{
<java statements> // body of while-loop
}
The above syntax looks simpler than a for-loop but in fact it is more complicated to use. This is because the while-loop does not automatically do the initialization and update. Instead, you the programmer must provide these as part of the normal code.
Example 1: Print the numbers from 1 to 100
int i = 1; // must initialize loop-variable
while (i < 100) // loop condition
{
outputBox.printLine(i);
i++; // must update loop variable
}
Note:
Example 2: Error Detection: Here is an example where a for-loop will not work.
int ans = inputBox.getInteger(
"Enter a number between 1 and 10.");
while (ans > 10 || ans < 1)
ans = inputBox.getInteger("Sorry, that was not "
+ "between 1 and 10. Please try again.");
Example 3: Iterating an equation.
Consider the mathematical equation
f(x) = 3x-1.
What happens if you start with an arbitrary number x, set x = f(x), and compute f(x) again?
f(1) = 3*1 - 1 = 2 f(f(1)) = f(2) = 3*2 - 1 = 5 ...
Write a while loop that iterates the above equation until either 1) there have been 10 iterations, or 2) the value is above 100.
int x = inputBox.getFloat("Enter a float."); int count = 0; while ( count < 10 && x < 100) { x = 3*x - 1; count++; } outputBox.printLine("The result is " + x);
What if I were to color a number line red for every starting value of x that leads to a number over 100, and color the black otherwise, what would the line look like?
This is how fractals are computed, except that we work in the complex plane instead of the number line.
Iterate f(z) = z*z + c, where z and c are complex numbers.
For Practice: Rewrite all of the for-loops that we looked at earlier - use while loops instead.
Write a program that fills out the screen with x's 10 wide and 20 long.
for (int y = 0; y < 20; y++) {
for (int x = 0; x < 10; x++)
outputBox.print("X");
outputBox.skipLine(1);
}
Modify this so that it prints out triangles with the following shapes:
In while-loops, the loop variable is tested at the beginning of the loop. Sometimes it is more convenient to test at the end of the loop instead. This insures that the loop is executed at least once.
For example (here, zero is called a sentinel):
outputBox.printLine("Enter numbers you want to add. " +
" When you are done, enter a zero.");
int num = 1; // must initialize to something other than 0
int sum = 0;
while (num != 0)
{
num = inputBox.getInteger("Enter your number: ");
sum += num;
}
outputBox.printLine("The sum is " + sum);
Alternatively, one could use
outputBox.printLine( "Enter numbers you want to add. " +
" When you are done, enter a zero.");
int num = 0;
int sum = 0;
do
{
num = inputBox.getInteger("Enter your number: ");
sum += num;
} while (num != 0);
outputBox.printLine("The sum is " + sum);
The above code does not depend on the arbitrary initial value of num since num is not tested until it has a value entered by the user.
Error correction, revisited:
int ans = inputBox.getInteger("Enter a number between 1 and 10.");
while (ans > 10 || ans < 1) {
ans = inputBox.getInteger("Enter a number between 1 and 10.");
}
The above code must duplicate the question. A better way to write this would be:
int ans = 0;
do {
ans = inputBox.getInteger("Enter a number " +
" between 1 and 10.");
} while (ans > 10 || ans < 1);