13 loops conclusion


#1

Well guys,

I've tried to do a code that counts the number of people above 30 yo and the number of people bellow 30 yo.

My code runs however evaluates to wrong answers, it must be 4 bellow 30 yo and 4 above 30 yo.

my code:

var age = [21, 33, 40, 29, 43,18,16,48];
var j;
var a =0;
var b =0;

var count = function(x,y){

for(j = 0; j < age.length; j++){

if(age[j] < 30)
{
    x +=j;
}
else
{
    y += j;
}

}
console.log("There are " + x + " people below 30 yo!");
console.log("There are " + y + " people above 30 yo!");

};

count(a,b);

evaluates to:

There are 14 people below 30 yo!
There are 14 people above 30 yo!


#2

I've changed to:
var age = [21, 33, 40, 29, 43,18,16,48];
var j;
var a =0;
var b =0;

var count = function(x,y){

for(j = 0; j < age.length; j++){
console.log(age[j]);
}
for(j = 0; j < age.length; j++){
if(age[j] < 30)
{
x +=j;
}
else
{
y += j;
}
}
console.log("There are " + x + " people below 30 yo!");
console.log("There are " + y + " people above 30 yo!");
};

count(a,b);

evaluates to:

21
33
40
29
43
18
16
48
There are 14 people below 30 yo!
There are 14 people above 30 yo!


#3

if(age[j] < 30)
{
    x +=j;
}
else
{
    y += j;
}

I'm not sure why you're incrementing by " j ". When you increment by j you're adding whatever number j is to your variable.

Why don't you just increment by 1 instead? Constants are much less confusing and in this example, the only thing that will work.

if(age[j] < 30)
{
    x += 1;
}
else
{
    y += 1;
}

#4

That's it

Thank you so much