The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 115 C

CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes
Stuart C. Shapiro
Spring, 2001


Loops

Reading
Brown U. Notes, Chapter 9
Barnes, Chapter 7

While statement
while (condition) statement
If the condition is true, execute the statement, and repeat.
If the condition is false, don't execute the statement, but continue with the statement following the while statement.

Do statement
do statement while (condition);
Execute the statement. If the condition is true, repeat.
If the condition is false, don't execute the statement again, but continue with the statement following the do statement.

See Example code.

Additional topics introduced in the example code:

New variables may be declared in any block.
Their scope is limited to the block in which they are declared.
It is illegal in Java to declare another variable with the same name in a nested block.

NGP.Utilities.randomNumber(i,j)
returns a "random" int, x, i <= x <= j.
Note, a computer program can only generate a pseudorandom number.

public void paintImmediately(int x, int y, int w, int h)
"Paint the specified region in this component and all of its descendants that overlap the region, immediately." [From the javadocs.]
Used to make sure that the animation is seen.

Path planning: To make sure that object o1 does not overlap object o2, consider where the reference point for o1 (its Location) may not be.

For statement
for (initialization; condition; update) statement
First execute the initialization statement. Then, if the condition is true, execute the statement followed by the update statement. Then repeat.
Whenever the condition is false, don't execute the statement, but continue with the statement following the if statement.

The scope of variables declared in the initialization statement is the entire for statement.

A paradigm for loop:

bsh % for (int i = 0; i<5; i++) print(i);
0
1
2
3
4

First Previous Next

Copyright © 2001 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <shapiro@cse.buffalo.edu>