T
PRO
2 weeks ago
Thomascountry asked

What does this mean: for (int side : sides)?

Sudip Bhandari
Expert
2 weeks ago

Hi there! for (int side : sides) is a common way of using a for-each loop in Java to iterate over elements in an array or a collection.

Let's break it down:

  • sides is an array of integers. In our context, it represents the lengths of the sides of a polygon.

  • int side declares that each element from the sides array will be treated as an integer and named side during each iteration of the loop.

  • for (int side : sides) means "for each integer side in the sides array, do something..." In this case, we are summing all the side lengths to calculate the perimeter of a polygon.

This code snippet inside the loop:

perimeter = perimeter + side;

...adds the current side value to the perimeter. After iterating through all the sides in the array, the variable perimeter will hold the total sum, representing the perimeter of the polygon.

Hope this helps clarify things! Feel free to ask if you have any more questions!

Java
This question was asked as part of the Learn Java OOP course.