CSCI A201/A597 and I210

Lecture Notes Twelve

Second semester 2000-2001


Loops.
What is the purpose of a while loop? To execute a statement while a condition is true.

Let's see some examples. Here's one that prints the first n numbers, where n comes from the user:
ConsoleReader console = new ConsoleReader(System.in); 
int n = console.readInt(); 
int i = 0; 
while (i < n) {
  System.out.println(i); 
  i += 1; 
}

Very good. What do you think of this one?
int year = 0; 
while (year < 20) {
  double interest = balance * 0.05;
  balance = balance + interest; 
}
Almost good, except it's an infinite loop.

What did I forget? The year doesn't change.

OK. What is the purpose of a for loop? To do what while does, except in a more systematic manner.

In what way? It clearly distinguishes an initialization step, the condition that needs to be true for the loop to keep going, and what we do from one step to the other.

Is this what you mean?
Yes, this is printing a line of 10 asterisks.

Could you do that with a while statement?
Yes, and here's how:
i = 0;
while (i < 10) {
  System.out.print("*");
  i = i + 1;
}

The for and while statements are equivalent. Yes, and this makes for good exercises.

What's the purpose of a do-while? It lets you do the body once, first.

Can we see an example? First the syntax:
do {

  statement

} while ( condition ); 

Very good, now the example. OK. Here's a snippet of code that adds all the numbers that the user types in and then reports the sum.

Does this go on for ever? The program ends when the user types a value of 0 (zero).

So you use a sentinel. Yes, the value 0 (zero) acts as a sentinel in this case.

This is only a convention, right? Yes, but it works for us. We can change it if it doesn't, but for this example it would be fine if I assume that the user signals the end of input this way.

Yes, it would be fine for this example. Then here's the program:
int sum = 0;
do {
  int number = console.readInt(); 
  sum = sum + number; 
} while (number != 0); 
System.out.println(sum); 

Can you do this with a while or a for loop? I can but it would be a bit un-natural to have to test first.

So do-while works better in this case. Yes, since we need to get the input first to test and see if we keep going or not.

And 0 (zero) is such a great sentinel for addition. Yes, you can add it to the sum and test it only afterwards.

How do you break a loop? Use the break statement.

What's continue doing? It just resumes the loop from that point.

How often are you likely to use these? Not often (break and continue, that is) but in some situations they can come in really handy.

OK, let's do an exercise. Let's see it.

What's this code doing?
int i = 0; 
while (i < 10) 
  i += 1; 
Just going through the first ten integers I suppose.

Correct. What does this one do?
int i = 0; 
while (i < 10) ;
  i += 1; 
Doesn't it do the same thing?

Don't you see a difference? Ah, the semicolon -- that's an infinite loop now.

Tricky. Indeed.

You have to be careful. How do you write 10 asterisks on a line.

Use a for loop. How do you write 10 such lines?

Use a for inside a for?
Yes, here's a diagram:

And how does the code look?
for (i = 0; i < 10; i++) {
  for (j = 0; j < 10; j++) {
    System.out.print("*"); 
  } 
  System.out.println(); 
} 
And the diagram again:

So these are nested loops. Yes, nested for loops.

Can you draw a square of asterisks of any size? Yes, just replace 10 in the code above by the size.

Can you make it hollow? With no stars inside?

Yes. I'd have to distinguish between the border and the inside, and print spaces inside and stars on the border.

Can you do that? I can.
public class Square {
    public static void main(String[] args) {
	ConsoleReader console = new ConsoleReader(System.in); 
	System.out.print("Enter the size: "); 
	int size = console.readInt(), i, j;
	for (i = 0; i < size; i++) {
	    for (j = 0; j < size; j++) {
		if (i == 0 || j == 0 ||
                    i == (size - 1) ||
                    j == (size - 1)) {
		    System.out.print("* ");
		} else {
		    System.out.print("  ");
		}
	    }
	    System.out.println();
	}
    }
}

How does it work? There you go:

frilled.cs.indiana.edu%java Square
Enter the size: 4
* * * * 
*     * 
*     * 
* * * * 
frilled.cs.indiana.edu%java Square
Enter the size: 8
* * * * * * * * 
*             * 
*             * 
*             * 
*             * 
*             * 
*             * 
* * * * * * * * 
frilled.cs.indiana.edu%java Square
Enter the size: 10
* * * * * * * * * * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
* * * * * * * * * * 
frilled.cs.indiana.edu%

Looks good. Thanks. Lab notes contain all the details.

So here's a more appropriate challenge for you. Oh, no...

Write a program that produces an "E" whose size is user-defined. Can you draw that for me?

There you go:
Three borders and half of a middle line... And the user inputs the size?

Yes. Not bad, not bad at all. Could have been much harder.

I agree. I know you do.

Yes: X, 4... Well, let's not even get into that now.

Sure, let's wait for the lab. I can hardly wait.

Last updated: Feb 14, 2001 by Adrian German for A201