VIPIN K.

asked • 04/14/23

FOR 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!


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.
Report

04/15/23

2 Answers By Expert Tutors

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.