0

This is just a simple multiplication program using an if / else and for loop. Re - entering a positive number from a prompt and assigning it to the num variable which the for loop should use is breaking the program.I’ m not sure why it is incorrect. ? Perhaps you could tell me the best way to do this using the if / else and for loop. Any help much appreciated.

//Array variable and counter variable

var multi = new Array();

var Counter;

//Enter a number between 1 and 12 and hold in num variable

num = prompt("Enter a number between 1 and 12");

//Check if number is less than zero
//Reenter positive number

if (num < 0) {
    var num = prompt("Enter a number greater than zero");
} 
else {
    //Number entered by user multiplied by counter value
    for (Counter = 1; Counter <= 12; Counter++) {
        multi[Counter] = num * Counter;
    }
    //Loop to display number that is being multiplied each time 
    for (Counter = 1; Counter <= 12; Counter++) {
        document.write(Counter + " x " + num + "  = " + multi[Counter] + '<br/>');
    }
}
8
  • It should be var num instead of num and then num instead of var num. Commented Oct 10, 2015 at 14:41
  • And document.write overwrites the document Commented Oct 10, 2015 at 14:42
  • why are you using two diff loops you multiply and display in one for loop right? Commented Oct 10, 2015 at 14:42
  • var num; do { num = prompt("Enter a number between 1 and 12"); } while (num < 1 || num > 12); Commented Oct 10, 2015 at 14:42
  • What does "breaking the program" mean, what exactly doesn't work ? Commented Oct 10, 2015 at 14:44

1 Answer 1

1

This can be simplified at the same time as fixing your code.

The reason entering a negative number was causing the code to fail was because you would never hit the else block and so never run the intended code within it.

As suggested by melpomene a do/while loop will serve you well here.

You also don't need 2 separate for loops, they can be condensed into one.

var num;

do {

  // Enter a number between 1 and 12 and hold in num variable
  // Check if number is not between 1 and 12 and re-enter
  num = prompt("Enter a number between 1 and 12");

} while (num < 1 || num > 12);

// You can define your counter variable within the for loop
for (var counter = 1; counter <= 12; counter++) {

   document.write(counter + ' x ' + num + '  = ' + (num * counter) + '<br/>')

}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much Josh. I didn't realise I was never hitting the else block. I spent a lot of time on this, pitfalls of being a new programmer.
No problem - keep at it!

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.