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?
-
Have you even try this yourself?Aleksei Zabrodskii– Aleksei Zabrodskii2012-04-21 03:09:42 +00:00Commented 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 basicjonathan miller– jonathan miller2012-04-21 03:37:04 +00:00Commented Apr 21, 2012 at 3:37
-
1I'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.Aleksei Zabrodskii– Aleksei Zabrodskii2012-04-21 12:42:37 +00:00Commented 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.Will Klein– Will Klein2012-04-21 17:41:51 +00:00Commented Apr 21, 2012 at 17:41
Add a comment
|
4 Answers
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
Will Klein
I cleaned up the code very slightly. Thank you for accepting, let me know if you have any questions about the code.
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
Will Klein
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.