December 21, 2024

Answer to JavaScript Exercise Q3

 

//get the number and convert and assign it in one line
var inNum = parseFloat(window.prompt('Enter a number' , ''));
/*
//this takes a few extra lines but is clearer
var inNum;
inNum = window.prompt('Enter a number' , '');
inNum = parseFloat(inNum);
*/
var incNum = inNum;
for (var i=1; i <=5; i=i+1)
{
  incNum = incNum + 2;
  document.write(inNum + ' plus ' + (i * 2) + ' equals ' + incNum + '<BR>');
}

Notes:

  • The for loop increments the counter variable i by use of
    i=i+1
    You could write i++ but M150 avoids the use of this operator
  • As with so many programming problems there are many alternative solutions. For example a while statement can be employed, although a for loop is the obvious option since the number of loops is known in advance (i.e. 5)
    //same code as above
    var i = 1; //declare and initialize a counter
    while (i <=5)
    {
       incNum = incNum + 2;
      document.write(inNum + ' plus ' + (i * 2) + ' equals ' + incNum + '<BR>');
      i=i+1;
    }

 

 

 

 

 

Back « JavaScript numbers

Up to top of page