[FAQ] and some Explanations about Loops

This is more or less a copy of the FAQ in the Archive just to keep it easier to find it and reanble the response functionality:
https://www.codecademy.com/forum_questions/5478568f282ae322d6006028

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.

Example
console.log("get the number of times a coin is not heads");

// get randomly either 0 or 1
var coin = Math.floor(Math.random()*2); 
var counter = 1; //count "coin flips"
while(coin != 1){
    coin = Math.floor(Math.random()*2);
    counter++;
}
console.log(counter);

console.log("Force the user to input correct password");
var pw = prompt("Please enter your password");
while(pw != 12345){
    pw = prompt("Please enter your password");
}

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:

Example
console.log("get the number of times a coin is not heads");

// get randomly either 0 or 1

var counter = 0; //count "coin flips"
do{    
    var coin = Math.floor(Math.random()*2);
    counter++;
}while(coin != 1);
console.log(counter);

console.log("Force the user to input correct password");
do{
    var pw = prompt("Please enter your password");
}while(pw != 12345);


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.

Example
console.log("Count from 0 to 10 with a stepwidth of 1:");
for(var i=0;i<10;i++){
    console.log(i);
}

console.log("Count from 12 to 36 with a stepwidth of 2:");

for(var i=12;i<37;i+=2){
    console.log(i);
}

console.log("Countdown from 10");

for(var i=10;i>0;i--){
    console.log(i);
}
7 Likes

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.

5 Likes

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.

1 Like

Number 10 expects us to do a ‘do while’ loop with a function in it as well. No part of the course shows us how to set this out and unfortunately the hint doesn’t either, which isn’t helpful.

I did not find your info helped with this issue.
Can you please provide an example of an answer to number 10 in the form the program expects?

3 Likes

I’ve encountered this problem as well in many posts but to be honest I don’t get the trouble about it. This is not a special or new concept that was never introduced. There was a whole lesson covering functions and this is the 2nd lesson covering loops and this is one of the last exercises in this lesson. And the step of combining them is rediculously easy:

this is a function:

var name = function(){
    //your code
};

and this is a do while loop:

do{
     //your code to print and avoid an infinite loop
}while(condition);

Now write a working do while loop and put it in where I wrote “your code” in the function. So there isn’t even a real interaction between function and loop necessary. Is it really just the word “function” that let’s people freak out?

I see that people really have a problem with it but I cannot see why. If this gives you headache than you probably have real lacks in understanding how functions work, do you? I’d really appreciate a response about what you see are the problems about this.

But if this get’s longer I’ll move it to a seperate thread and I’m not going to write a specific answer to exercise x/y in this thread. The idea is just to explain some concepts, contexts and some common errors not to give a walkthrough for the exercises.

1 Like

Many thanks for posting these! It explains some concepts more clearly than the lessons and it’s actually a nice reference to refer to back to when I can’t quite remember certain points.

2 Likes

A post was split to a new topic: “Oops, try again. It looks like one of your loops isn’t quite right. Check the Hint if you need help!”

does a while loop run “until it’s proven false?” or can it also run “until it’s proven true,” if it started out as false?

must a do-loop start out as false? or can it start out true and then print the statement until its is changed to false? - would that cause it to stop?

1 Like

Well regular code runs like this:

statementA;
statementB;
statementC;
....

From top to bottom one statement is executed at a time. Now what loops do is pretty much something like this:

#position_marker:
    statementA;
    statementB;
    statementC;
if(condition){
  jump back to #position_marker;
}

So when the condition is true you just go back to the marked position and repeat the process. So as you end up where you started, well you performed a loop. And this goes on and on and on as long as the condition is true so to break the loop you need to make sure that the condition is false when it is checked.
Side note: Do not take this literally and try to use jump marks and go to statements, there is a reason why high level languages use loops instead of these. You might google “spaghetti code” if you want to know why it is discouraged to do so.

So to answer your question no the condition needs to be true for the loop to function. But of course you could set up a condition that is true if the input is false e.g. !input

And on the do while part: Well no as said above it’s just a regular while loop that is written a bit differently:

do stuff; // executed once no matter what
while(condition){
    do stuff;
}

here the place holder do stuff is written twice. When you think that it could hold the place for a huge number of statements you might want to get rid of the redundancy of writing them twice. Now that is what the do while loop is for:

do{
    do stuff;
while(condition);

exact same meaning as the one above but with just one do stuff.

I guess the exercises wants to emphasize on the fact that the code after do is executed once even if the condition is false, but that doesn’t mean that it has to be false as said just a regular while loop. I made some examples in the link above that should emphasize the similarity between the while and do while loop. But if you have further question go ahead.

1 Like

Hi
Kindly help, am having a problem in using the if/else statement, could you please advice on how to arrange the {} after every condition??
Kind Regards
Odhiambo Jr.