1

New to JS. I'm trying to change my for loop to a while loop. It prints the factors of a number, but for some reason, the while loops causes the webpage to stop responding. Any help is appreciated.

var num, i = 1,
  array = [];

num = parseInt(prompt("Please enter a number:"));

while (i < num) {
  if (num % i == 0) {
    array.push(i);
    i++;
  }

}
alert("The factors of " + num + " are: " + array + " and " + num);

1
  • You might wanna give num a value if the prompt did not return a numeric value or not a value at all, you might end up with NaN which would also fall into the case of i < num returning false Commented Mar 5, 2017 at 18:42

2 Answers 2

4

Move the incrementation of i variable outside the if condition. Else - the while loop will be stuck when the num is not divisible by specified i.

For example - if num is 5 and i is 2, the loop will be stuck because the if condition is not fulfilled - that's why i won't be incremented - and then we will experience an infinite loop.

var num, i = 1, array = [];
num = parseInt(prompt("Please enter a number:"));

while (i < num) { 
   if (num % i == 0) {
      array.push(i);
   }
   i++;
}
alert("The factors of " + num + " are: " + array + " and " + num);

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

1 Comment

so simple xd. Thank you.
0

You increment i only if the condition of the "if" block is true. If that condition evaluates to false, i can't be incremented, and therefore the loop never ends.

if (num % i == 0) {  // <some value except 0> % 1 == 0 -> false
    array.push(i);
    i++;
}

so try:

while (i < num) {
    if (num % i == 0) {
        array.push(i);
    }
    i++; // now i can be incremented regardless of the condition in the "if" block.
}

Comments

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.