First Summer 2004


Lecture Notes Twelve: 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 the value of 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 code fragment that adds all the numbers that the user types in and then reports the sum of all these numbers.
int sum = 0;
int number; 
do {
  number = console.readInt(); 
  sum = sum + number; 
} while (number != 0); 
System.out.println(sum); 

Does this go on for ever? No. Our ad-hoc convention is that the program
frilled.cs.indiana.edu%webster ad-hoc
1ad hoc \(')ad-'ha^:k, -'ho^-k; (')a^:d-'ho^-k\ adv
[L, for this]
(1659)
:for the particular end or case at hand without consideration of wider
     application 
frilled.cs.indiana.edu%
... ends when the user types a value of 0 (zero).

So you use a sentinel. Yes, the value of 0 (zero) acts as a sentinel in this case, guarding the end of our processing.

This is only a convention, right? Yes, but it works for us.

Can you do this with a while or a for loop? Yes, but you'd have to test first.

And do-while just as well in this case. Plus, zero is such a great sentinel for addition!

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 real 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 10 integers I suppose.

Correct. What's this one do? <snicker>
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? Take a look.
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?
Here 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" (uppercase)

  • 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.
public class E {
    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 || 
		    i == (size - 1) ||
		    j == 0 ||
		    (i == (size - 1) / 2 && j < (size / 2))
                   ) {
		    System.out.print("* ");
		} else {
		    System.out.print("  ");
		}
	    }
	    System.out.println();
	}
    } 
}
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.
frilled.cs.indiana.edu%java E
Enter the size: 10
* * * * * * * * * * 
*                   
*                   
*                   
* * * * *           
*                   
*                   
*                   
*                   
* * * * * * * * * * 
frilled.cs.indiana.edu%java E
Enter the size: 19
* * * * * * * * * * * * * * * * * * * 
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
* * * * * * * * *                     
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
*                                     
* * * * * * * * * * * * * * * * * * * 
frilled.cs.indiana.edu%

Last updated: May 16, 2004 by Adrian German for A201