0

I have to create a while loop displaying the integers from 1-20 but only 5 integers per line. I can't get the 5 integers per line part. What is the best way to do that?

4
  • Have you even try this yourself? Commented Apr 21, 2012 at 3:09
  • yes but not like the way you had it. as you might have noticed from my question my coding right now is rather basic Commented Apr 21, 2012 at 3:37
  • 1
    I'm asking because posting your pieces of code may work better from learning point-of-view. You'll be able to understand which mistakes you made, how to avoid it in future, etc. In similar "hello-world" exampled that could be not so obvious, but IMO it always better to post something you did yourself. Commented Apr 21, 2012 at 12:42
  • I agree with elmigranto, try posting what you have so people can provide a solution AND help you with your own code. I understand being new to this though. At the very least, ask questions on the answers if you have any. Commented Apr 21, 2012 at 17:41

4 Answers 4

1

Check if it's the next item after a multiple of 5 and if the current item is not the first item. If it is, also print out a newline. For example:

for(var i = 1; i <= 20; i++) {
     print(i); // Or however you're outputting it

     if(i % 5 === 1 && i > 1) {
         print('\n');
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a solution that builds a string and displays an alert box with the result.

var i = 0, result = "";

while (i++ < 20) {
    result += i + " ";

    // check to see if we're at 5/10/15/20 to add a new-line
    if (i % 5 === 0) {
        result += "\n";
    }
}

alert(result);

jsFiddle to test: http://jsfiddle.net/willslab/KUVkX/3/

1 Comment

I cleaned up the code very slightly. Thank you for accepting, let me know if you have any questions about the code.
0

You can do...

if ( ! (i % 5)) {
    // Create new line.
}

jsFiddle.

Comments

0

See no while loops in previous answers =)

function generateLine(start, nElements, separator) {
  var i = start;
  var range = [];
  while (range.length < nElements) range.push(i++);
  return range.join(separator) + '\n';
}

function generate(start, end, elementsInLine, inlineSeparator) {
  var lines = [];
  while (start < end) {
    lines.push( generateLine(start, elementsInLine, inlineSeparator));
    start += elementsInLine;
  }

  return lines.join('');
}

console.log( generate(1, 20, 5, ' ') );

1 Comment

This is a nice solution, I thought of writing a generic function as well. I wasn't sure it would be easy enough to understand though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.