### Thread: Why is this running infinte times?

1. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2012
Posts
75
Rep Power
3

#### Why is this running infinte times?

Code:
```int main ()
{
int i, n;

for (n = 2; n <= 2; n++)
{
for (i = 2; i <= n; i++)
while (n % i == 0)
{
printf ("%d\n", i);
n /= i;
}
}
}```
This simple loop is running infinitely. I've been debugging for hours now and cannot find a mistake. It must be a simple error but I'm fed up.
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Location
/dev/null
Posts
164
Rep Power
19
Let's trace through what's happening:

1. First n = 2; it goes inside the outermost for-loop
2. Then i = 2; it goes inside the next inner for-loop
3. Now, n % i = 2 % 2 = 0; it goes inside the innermost while-loop
4. Prints i
5. Calculates n = n / i = 2 / 2 = 1. Now n = 1.
6. Next iteration in while loop: n % i = 1 % 2 = 1 != 0; thus control comes out of while loop and into the inner for-loop.
7. i++ = 2 + 1 = 3. Condition is checked: i<=n => 3<=2 => NO; so control comes out of the inner for-loop and into the outermost for-loop.
8. n++ = 1 + 1 = 2 (remember, we did n = n / i in the while loop). Condition is checked: n<=2 => YES; now you're in step #1.

And hence infinite loop.
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Dec 2012
Posts
75
Rep Power
3
Thank You! Seriously I needed some help, even though it was simple sometimes you just need a fresh mind.