Reading:
At this point, we’re primarily interested in counting
for
loops. The other loops are useful as well, but the
for
loop will be a real workhorse through the rest of the semester. Make sure that you understand how to use it
productively.
Miles | Kilometers |
---|---|
1 | 1.609 |
2 | 3.218 |
... | ... |
10 | 16.090 |
What do the following code segments do?
// Segment 1 for (int i = 0; i < 500; i += 2) { System.out.println(i); } System.out.println(i); // Segment 2 for (int i = 1; i > 10; i++) { System.out.println(i); } // Segment 3 int i = 99; for (; i > 1; i--) { System.out.println(i); }
Explain what happens with these statements and why. If the statements don’t work as one might expect, modify them so that they do.
Convert the
for
loop in the following code segment to an equivalent forever loop.
int sum = 0; for (int i = 0; i <= 100; i++) { sum += i; } System.out.println(sum);
This section is optional.
The examples shown above and many of the examples in Section 7.2 of the text will work in either Processing or in Java. However, Processing doesn't easily support text input, so the text examples that use the Scanner class will not work in Processing. This is part of the reason that the materials transition to Java; you need experience with console-based input.
The text will continue to include Processing-based examples, which can be made to work in pure Java (see Chapter 11), but the focus has now shifted to pure Java and Java Integrated Development Environments (IDEs).
Skip this section for now, we’ll return to it later in the course.