Need help with a While loop, please

Just learning JS. Here’s the code:

var count = 1;
while(count < 11)
{
  document.write(count + " ");
  count++;
}

And the output is:

1 2 3 4 5 6 7 8 9 10

How can I modify the loop in the example above to output even numbers between 0 - 100.

Hi @AlexTechFlow try the following, if there is something not clear about it please ask:

var count = 1;
while(count <= 100) {
	document.write(count + " ");
	count+=2;
}

Hope it helps

Hi there AlexTechFlow,

try it like this, without the document.write()

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
 }
#info {
    max-width: 43em;
    padding: 1em;
    margin: auto;
    border: 0.06em solid #999;
    box-sizing: border-box;
    background-color: #fff;
 }
</style>

</head>
<body> 

<div id="info"></div>

<script>
(function( d ) {
   'use strict';

   var count = 0;

   while( count <= 100 ) {
        d.getElementById(  'info'  ).appendChild( d.createTextNode( count + ' ' ) );
        count += 2;
  }
}( document ));
</script>

</body>
</html>

coothead

2 Likes

That’s a good idea to use <= 100, as it gives you a better understanding that 100 is the last value that it will use.

This will print odd numbers, you start from 1 and increment by 2, 1 + 2 = 3 + 2 = 5 and so on.
Either use coothead’s approach or modolus operator to check for even number.

Best regards,
@marklenon95

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