This forum is now read-only. Please use our new forums at discuss.codecademy.com.

3324 points
5139256f6a90a0ef75009600_690502710
Submitted by
haxor789
almost 4 years ago

[FAQ] and some Explanations about Loops

As this section doesn't have a FAQ so far lets make some in this thread. Feel encouraged to extend it, but please post questions and in particular questions about your code as a seperate question in another thread to keep this readable.

Now lets start with the explanation of loops in general.
I'd say: "The idea of a loop is to group reoccurring code that is pretty similar and executed in a row in one structure."

The while loop:

Syntax:

while(condition){
    statements;
}

How to use: A while loop is pretty simple it runs the code in the {} while the condition is true. So its basically a loop of:

check condition --> run code / exit --> check condition --> run code / exit --> ...

When to use: As the while loop is just a reoccuring if condition it does not need to know how often it is executed or still has to be executed so if you don't know it either use the while loop.

Examples:
http://labs.codecademy.com/CcTP/2#:workspace

The do-while loop:

Syntax:

do{
    statements;
}while(condition);

How to use: Write the code you want to loop over in the {} between do and the while(condition) where I wrote statements, this code is executed once without any condition and then its the same loop as for the while loop:

execute statements > check condition -> jump back to do / exit
-> check condition --> ...

When to use: The do-while loop is some kind of inverted while loop where the {} is placed befor the condition. It's main purpose is to avoid repeating yourself. See the examples for more.

Examples: Pretty much the same as for while but shortend, if you do not need the statements inside of the loop to be executed once unconditioned take the while loop otherwise this is a good alternativ:
http://labs.codecademy.com/CcTP/1#:workspace

The for-loop:

Syntax:

for(initalize;condition;manipulate){
    statements;
}

How to use:
initialize: this part is executed only once before anything else in the loop and is regularly used to initialize the counting variable e.g. var i=0;
condition:this part is executed before the code in the {} is executed or skipped. Normally its the condition when to stop e.g. i < stoppingValue
manipulate:this part is executed after the execution of the stuff in the {} and normally its used to change the value of the counting variable to get it nearer to the stopping value e.g. i++

The loop is:

initialize -> check condition --> run code /exit --> manipulate --> check condition --> run code /exit --> manipulate --> ...

When to use: For loops in general is used when you know the number of loops you want to do. In this case you can imagine a starting value, a stopping value and a stepwidth which this loop manages all nicely in one line.

Examples:
http://labs.codecademy.com/CcSv#:workspace


12 votes

permalink

Remarks about exchanging loops

All loops can be exchanged with one of the other loops e.g.

for(int i=start;i < end;i++){
    statements;
}

could be written with the same meaning as:

var i = start;
while(i <end){
    statements;
    i++
}

or

var i=start;
do{
    if(i < end){
        statements;
        i++;
    }
}while(i< end);

But as you can see it means spreading your information on more lines using a while loop in this case and for a do while loop you even need to use an additional if to imitate the while loop. So in general you're better off using the loops that feels most intuitive for the purpose which are hopefully those situations which I mentioned under "When to use".

Some last words to using for loops as an exchange for other loops:

Your allowed to leave up to all 3 parts of the for loop (initialize, condition, manipulate)* empty, in this case, first of all think if this is a good idea, because probably a while loop would be better in this case, but if you try to do this, leave those 2 semicolon at their places so

for(;;){
statements;
} 

is a valid for loop, which is treated as an infinite loop so you need to find other ways to stop it.
(--> break;)

* I named these parts this way, because I think they are intuitive but if anyone knows the correct names for these parts feel free to mention them in the comments.

3324 points
5139256f6a90a0ef75009600_690502710
Submitted by
haxor789
almost 4 years ago

7 Comments

Cdf5b1ee557ca900d26cd471262623e5?s=140&d=retro Steven Rodriguez over 3 years ago

thank you for these. seeing them all together and the examples helped understand these a lot better.

53fb5a4a631fe97d2200a68a_712253049 RonandoL over 3 years ago

I often wondered about this as well as when is it best to use one loop over another. Thanks for the info.

53fb5a4a631fe97d2200a68a_712253049 RonandoL over 3 years ago

As I read through the rest of these explanations, I'm surprised at how they cut right to the bone of the issue with complete clarity. Thanks Haxor! This really helps!

5139256f6a90a0ef75009600_690502710 haxor789 over 3 years ago

Thank you!

Fe89b43e89ee7bef0819c69b6d8936a0?s=140&d=retro dsatech over 3 years ago

Really helpful! Was stuck until I found this explanation.

323ff57521877c103ae80a3f80505722?s=140&d=retro M4lkhut over 3 years ago

Seriously where was all this valuable info.? THX!

Eebf04b775629a37274789955b2951b6?s=140&d=retro kobetO over 3 years ago

Helped me too. Thanks!


4 votes

permalink

Do-While/While Loops!?

A rather common problem is the use of these I'd call them "Do-While/While-Loops". The problem is that they do not exist. If you have a close look at them:

var variable = true;
do {
    statements;
} while (variable);
{
    variable = false;
}

or

var variable = 0;
do {
    statements;
} while (variable< end);
{
    statements;
    variable++;
}

you'll realize, that it is just a do/while loop:

do {
    statements;
} while (variable);

and then you go on with this code:

{
    variable = false;
}

unfortunately the part that falsifies the condition is now part of the "unimportant" block of code (after the actual loop), which means you can not reach it before you finished the loop. As it enables the loop to finish but is only reached if the condition has already finished, this creates an infinite loop.

For an explanation how and why we use the {} after loops and condition have a look at my post here:
http://www.codecademy.com/forum_questions/52373a75548c3515940000dc

PS: Would be great if someone could explain why one would come up with this structure.

3324 points
5139256f6a90a0ef75009600_690502710
Submitted by
haxor789
over 3 years ago

3 Comments

Picture Tuangt over 3 years ago

I have tried to do something else than what the lesson has taught, but it didn't work. I came to the forum to see why and see that it has only the same example of the Do-While thing. I really want to know why, and how people going to use this loop actually.

Picture Tuangt over 3 years ago

because it seems like you can use other loop kind to do or create a function instead, if a variable in while() always need to be false.

5139256f6a90a0ef75009600_690502710 haxor789 over 3 years ago

In the initial post I tried to explain when to use a certain kind of loop and there are also links to examples for do/while loops. In the exercises it isn't really used "loop like" meaning the focus is on the fact that it executes the statement after do once no matter what the condition is. This is truly the interesting part of this loop but you're correct one could achieve the same behaviour by just using the statement without any loop. Could you be a bit more descriptive about your problem in another thread and post a link to this thread here?