### For loop isn't looping. Variable in failure.

I am trying to tally the prime numbers from 1-100000, and I think I'm on the right track. My issue seems to be with the second for loop, with the imbedded if and while statements. The program compiles, and the output is 0,1,2,3,5,7,9 etc. to 97. For some reason, the for loop in question executes j = 2 just fine, sets the multiples of 2 to false, but doesn't loop. I executed line by line, and int i ends up in failure, and has the value of a large negative number, even though int elim counts as anticipated. Also, I'm not sure if it is normal for an array or not, but when i went line by line, the value of my bool array was 0x0012feb8.

Also, double range was 100 in my last run and I changed it to 99 thinking that maybe I was out of the range of my array from 0-99, same results though.

I was able to find a couple solutions about non looping loops, but the ones I found didn't seem to apply. I appreciate any suggestions. Thanks in advance.

 ``12345678910111213141516171819202122232425262728293031323334353637383940`` ``````#include #include using namespace std; int main() { int elim = 0, j = 0, i = 2; double sqRoot, range = 99; bool numArray[100]; for(j = 0; j < range; j++) // initializes all values in the array to true numArray[j] = true; sqRoot = sqrt(range); j = 2; for(j = 2; j < sqRoot; j++) // progresses through array { if(numArray[j] == true) // decides whether selected array term is true or not { i = 2; while(elim < range) // makes non primes false { elim = i * j; numArray[elim] = false; i++; } } } for(j = 0; j < range; j++) { if(numArray[j] == true) { cout << j << endl; } } system("PAUSE"); return 0; }``````
Last edited on
It is not, actually, in the for loop. It's in the while... think about it. What does elim equal once you exit out of the while loop? What does it equal when you try to go back in?
I figured it was something simple that I was overlooking, thank you so much. When i reinitialize i, i will also reinitialize elim.

Thanks again!
Topic archived. No new replies allowed.