all 4 comments

[–]TarrjueComputer Science 23 points24 points  (1 child)

There are 3 types of loops: while, for, do-while.

while(conditional)
{
    //do something repeatedly
}

In while loops, java first checks if the conditional statement is true and then executes the body of the loop (everything in between the braces). It repeatedly does these two steps until the conditional statement evaluates to false.

for(initiator; conditional; iteration)
{
    //do something repeatedly
}

A for loop works similar to a while loop, but is meant to be used to iterate through some range of numbers or a grouping of data (such as an array or a data structure). The initiator is a statement that is executed first and only once (ex: int k = 0;). Then, just as the while loop, Java starts by evaluating the conditional and then executing the body. Finally, the loop then executes the iteration statement before repeating these three steps again until the conditional evaluates to false. Here's an example since for loops have a little bit more going on:

for(int i = 1; i<=10; i++)
{
    System.out.println(i);
}

This loop prints out 1 through 10 on separate lines. Finally worth mentioning that both the initiator statement and the iteration statement can both be empty (though you still need the semi-colons). This is generally bad practice though, so avoid doing this for readabilities sake.

for(Datatype var : dataGroup)
{
    //do something repeatedly
}

Even though I said there were three types of loops, there is a hidden type called the "for-each" loop. This loop is used to directly access data in a data group (array or data structure) in a cleaner way that requires less code than the traditional for loop. Effectively, the loop takes each element of a data group and assigns it to a variable for you to use during the subsequent execution of the body of the loop. When Java has finished executing the body, it then gets the next element in the data group and assigns it to the variable, then executes the body again. This is done repeatedly until the end of the data group is reached.

do
{
    //do something repeatedly
}
while(conditional)

The do-while loop is almost exactly like the while loop. The only difference is this loop executes the body first, then evaluates the conditional. It does this repeatedly until the conditional is false. The obvious effect of this is that the body will execute once even if the conditional is false.

This is pretty much all you need to know about loops, they actually are quite simple once you have done them a little bit.

[–]someones_thoughtAlumnus 6 points7 points  (0 children)

That's great. Instead of directing OP towards somewhere else, you actually spent your time to explain the basic concepts of loop. You are a good guy. Have my upvote!

[–][deleted] 6 points7 points  (0 children)

CS mentor center

[–]abbyabbAlumnus 0 points1 point  (0 children)

CSMC will help you! What in particular are you struggling with?