VIPIN K.
asked 04/14/23FOR loop question in Java
You need to implement this function public int countBlocks(int levels)
that takes the number of levels as an input argument and returns the number of blocks required to build a pyramid made up of that many levels.
Remember that for
loops help count up to a certain number (which is the value of levels
in this case) and inside the loop, the number of blocks for that level would be the result of multiplying the loop counter by itself (for example i*i
)
This means that if for every level, the number of blocks in that level was added to some variable total
then by the end of the loop the total number of blocks needed to build the entire pyramid would be in that total
variable and could be returned as the result of that function!
2 Answers By Expert Tutors
William M. answered 05/28/23
College Professor of C++ with 7+ years of teaching experience
```
public int countBlocks(int levels) {
// We'll accumulate our answer into this variable. It starts at 0, since we haven't considered any levels yet.
int total = 0;
// We need to generate the number of blocks necessary for each level, starting at level 1
// and ending at levels. We're given the formula for the number of blocks needed for a level, i: i * i.
// After we calculate the number of blocks needed for a level, we add that value to our variable "total"
// because we need that many more blocks in total.
// When we're done looping, total should contain the sum of all the blocks necessary for each level, which
// is the value the problem wants us to return.
// So for each level, i, in the loop, calculate the number of blocks for that level, i * i, and add it to total
for (int i = 1; i <= levels; ++i) {
total += i * i;
}
return total;
}
```
I think the problem designer didn't care for you to think about this next thing I'm going to suggest you consider, but it's worth considering. What's the behavior if someone calls countBlocks(0)? Or countBlocks(-1);? Does that seem okay?
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
VIPIN K.
Many thanks, Mark, for taking the time to respond. I am very new to Java, and was making an elementary syntax error earlier. I did figure out the solution (the same as yours) a little while back after fixing the illogical syntax I had used. I do also see that ++i is ok to use, as well as i++. Good to know. Thank you for raising the question about countBlocks(0) and countBlocks(-1). Integer values <= 0 should be fine for the purpose of running through the for loop, but not for building a pyramid. :) I am unable to come up with anything more insightful than that.04/15/23