Question about 'while' loop on review lesson


#1


https://www.codecademy.com/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661


Hello to everyone!

On the review lesson of 'for'/'while'/'do' I wrote the attached code.
'for' and 'do' loops execute fine but the 'while' loop prints at the console the result of the code for some numbers more than one time.
This is the printout of all the code:

''for' nr are: 5
'for' nr are: 16
'for' nr are: 95
'for' nr are: 457
'for' nr are: 78
'for' nr are: 65
'while' nr are: 65
'while' nr are: 65
'while' nr are: 16
'while' nr are: 16
'while' nr are: 95
'while' nr are: 4522
'while' nr are: 457
'while' nr are: 4564
'while' nr are: 78
'while' nr are: 78
'while' nr are: 65
'do' nr are: 0.8284266994848117
0.5645374970995312

Could, please, anyone advise me why this is happening.
Also, why does the console print out one more 'Math.random()' number (in the above example 0.5645374970995312) after the code print out is finished?

Thank you in advance!


// Write your code below!
var arra = [5, 9, 16, 2, 95, 4522, 457, 4564, 78, 1, 65];
//my 'for' code
for (var k = 0; k < arra.length; k+=2) {
    console.log("'for' nr are: "+arra[k]);
    };
//my 'while' code     
var s = 0;
while (s < arra.length) {
    if (arra[s] > 10) {
        var d = arra[s]
        }; 
    console.log("'while' nr are: "+d); s++;
    };
//my 'do' code
var f = Math.random();
do {console.log("'do' nr are: "+f); f = Math.random();}
while (f < 0.5);


#2

Your code is executed one instruction at a time. Do you think it should be doing something differently? If so, what?


#3

I cannot understand why the 'while' printout (console.log) is taking some numbers which are >10 (if (arra[s] > 10)) from the array called 'arra' and print them more than one time (like the nr 65, 16 & 78), since they are uniq in the array.
Thank you for your quick response!


#4

I think I found where the mistake was. The code that replaces //my 'while' code above should be:

var s = 0;
while (s < arra.length) {
if (arra[s]>10) {
console.log("'while' nr are: "+arra[s])
}; s++;
};

This seems to print out only one time every number of the array that is more than 10.

Thank you again and sorry for your time!


#5

You were printing that out regardless of whether the condition was satisfied or not, yes. And you had probably run the code earlier, therefore having defined d, with 65 being the last set value


#6

I'm not sure why the first code didn't match the criteria because I don't looked further since I found the alternative solution but I think, without trying it out yet, that "var d = arra[s]" should be before the "if" condition check and the check should be "if (d>10)".
I' ll try that also out as soon as possible.
Thanx again!


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.