Azib Yaqoob
Azib Yaqoob

Reputation: 37

JavaScript for Loop

Write odd numbers from 1 to 100.. And I used this piece of code for this:

var i=1;
for (i=1; i < 51; i = i + 1){

 document.write(i -1 + i );
  document.write("<br />");
  }

Now, can somebody please tell me if this code is right or I can make it better.

Upvotes: 0

Views: 11649

Answers (3)

CD..
CD..

Reputation: 74096

for (var i=1; i < 100; i += 2){
  document.write(i);
  document.write("<br />");
}

http://jsfiddle.net/kX8hn/

Upvotes: 9

Andrew Leach
Andrew Leach

Reputation: 12973

It's wrong and you can make it better. Start at 1 and count up to 100 in increments of 2:

for (var i=1; i < 100; i += 2){
  document.write(i);
  document.write("<br />");
}

The usual caveats about document.write() apply.

Upvotes: 2

Danilo Valente
Danilo Valente

Reputation: 11342

for (var i=1; i <= 100; i += 2)
    document.write(i + "<br />");

Upvotes: 4

Related Questions