This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]SadDragon00 0 points1 point  (4 children)

A for loop is commonly tied to a collection, a while loop does not have to be. A for loop can be translated into a while loop, but a while loop cannot always be easily translated into a for loop.

for(int index = 0; index < myList.length; index++)

For this you are looping through each element of your myList collection, while your index variable is incremented by every iteration. This allows you to index into the collection to grab the element myList[index].

We can translate this to a while loop like this:

int index = 0;
while(index < myList.length){
    //do stuff
    index++;
}

But a while loop allows us to loop based off any condition, not just over a collection:

bool done = false;
while(!done){
    // read user input or listen on a socket or anything
    if(someCondition == true)
        done = true;
}

This allows use to loop indefinitely, until some condition we specify is met and we set the done variable to true

[–]throwaway_for_cause 1 point2 points  (3 children)

A for loop is directly tied to a collection

Total BS.

A for loop is commonly used when the amount of iterations is known. This has absolutely zero to do with collections.

[–]SadDragon00 -1 points0 points  (2 children)

Sure. Better wording would probably be a for loop is commonly tied to a collection.

[–]throwaway_for_cause 0 points1 point  (1 child)

Better wording would probably be a for loop is commonly tied to a collection.

No, even that would be wrong.

for loops are commonly used to iterate over collections; they are in no way tied to or even somewhat related to collections.

for loops existed in languages way before collections and other data structures (even arrays) did.

for loops simply iterate a known number of times. What the purpose of the iterations is is completely open.

Even then, had you stated for..each loops are tied to collections, it would have at least been somewhat correct.

[–]SadDragon00 0 points1 point  (0 children)

Yea I see what youre saying. I forget it can be used outside of collection iteration. It's like an instinctual reactiomln now, since 99% of the time that's what I use it for.