Having now seen two types of loop (“For-each” and “while”), we’ll now turn our attention to the final type of Java loop: the “for” loop. Despite the name, for
loops are more similar in structure to while
loops than they are to “For-each” loops.
for
loops have the trickiest syntax of all the types of loops. Furthermore, they don’t provide any functionality beyond while
loops. You may be wondering: “Why bother?” The answer lies in fact that compact representation of for
loops reduces the chance of bugs such as infinite loops. With some experience, the syntax of for
loops will become less mysterious and reduced possibility of bugs will become more obvious.
Sections 4.3.5-4.4 (pp. 110-126) from the course textbook.
Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.
for
loop.while
and for
loops.The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.
for
loop (using a single array of pixels).for
loop.These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.
How many times will “Hello” be printed after executing the following code?
for (int t = 10; t < 20; t++)
{
System.out.println("Hello");
}
How many times will “Goodbye” be printed after executing the following code?
for (int q = 0; q <= 8; q = q + 2)
{
System.out.println("Goodbye");
}
Consider the following Java code:
int x = 0;
while (x < pixelArray.length)
{
pixelArray[x].setBlue(0);
x = x + 1;
}
If we wanted to write this code using a for
loop instead of a while
loop, what code will we have for the following parts of the for
loop: