Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 16800  / 9 Years ago, sat, february 7, 2015, 12:00:00

trying to brush up on some basic javascript and I'm wondering how you would solve this. I found a way but it's pretty ugly and I'd appreciate some more experienced eyes letting me know what they thing. Basically, just iterate over the numbers 1-100 and print all even numbers in groups of five on each line. So line one would be 2,4,5,8,10, line 2 is 12,14,16,18,20. Here is what I have so far:



var counter = 0;
var line=[];


for(var i = 0; i<=100; i++){
if(i%2==0){
if(line.length <5){
line[counter] = i;
counter++
}else{
console.log(line);
line=[];
counter=0;
line[counter] =i;
}
}
}
console.log(line);


Thanks so much!


More From » loops

 Answers
4

The problems that I see with the code is that you are looping from 0 instead of 1, and that you are not increasing the counter in the else block.



Fixing that you get:



var counter = 0;
var line=[];

for (var i = 1; i <= 100; i++) {
if (i % 2 == 0){
if (line.length < 5) {
line[counter] = i;
counter++
} else {
console.log(line);
line=[];
counter = 0;
line[counter] = i;
counter++
}
}
}
console.log(line);


Instead of looping from 1 to 100 and checking if the number is even, just loop from 2 to 100 in steps of two. You don't need the counter at all, you can push the items into the array. Instead of repeating the code that adds an item to the array in the if and else blocks you can just do it once after.



With those simplifications you get:



var line=[];

for (var i = 2; i <= 100; i += 2) {
if (line.length == 5) {
console.log(line);
line=[];
}
line.push(i);
}
console.log(line);

[#67917] Wednesday, February 4, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;