Student: OK so you mentioned that we have “accumulator” loops and we did a “best-so-far” loop. What are some other kinds?
Prof: Glad you asked! There are lots of tasks we like to do with arrays, and many involve loops, and many do have logical “plans” and even useful names. Let’s write a method that is a small change to
closestTo: averageDistanceTo. Based on the name, what do you think it does?Student: I guess it takes a point and averages up all the distances to that point?
Prof: Right! What do you think it will need to track?
Student: I guess the total distance, so we can divide it later?
Prof: Right! We’d call that a running-sum accumulator. What type do you think it would be, what’s a good name for it, and what’s a good initial value?
Student: I guess
double? Named total, starting at 0?Prof: Let’s try it.
Student: OK, I think I get that.
Prof: There are also counter loops, that, well, count something. For example, you could count how many Points are within a certain range of a target. What would the method header be for something like that?
Student: Hmmm maybe like
countNearby? And I guess it returns an int because that’s what a count is.Prof: Great, and the parameters?
Student: I guess another
Point target like we’ve been doing?Prof: Anything else? Did we talk about any other data in the problem description?
Student: Well you said “within a certain range”. I guess we need to pick that. Should it be a parameter?
Prof: You could try it that way!
Student: OK so
int countNearby(Point target, double range)Prof: Looks great. Let’s try to write it.
Student: I see. OK so we’ve seen running-sum, best-so-far, and counters. That’s a cool way to organize thinking about loops and arrays. I hadn’t thought of giving them those names before.
Prof: I hope it helps you write cool array programs!
Practice
Recall Pizza and PizzaOrder:
record Pizza(double inches, int costCents) {
double area() {
double radius = inches / 2;
return radius * radius * Math.PI;
}
}
record PizzaOrder(Pizza[] pizzas) { }Each of these PizzaOrder methods loops over its pizzas. Which kind of loop fits each one best?
int countCheaperThan(int limitCents) – how many pizzas in the order cost less than limitCents: Pizza largest() – the pizza with the biggest diameter: double totalArea() – how many square inches of pizza the whole order adds up to: