I am tackling an exercise that finds prime numbers under 1000. It compiles ok but terminates with abort trap 6 and I do not know why?
Can anyone please help!!
I was thinking off changing from a bool array to int vector andn setting all elements to 1...?
#include<iostream>
#include<vector>
int main()
{
bool primeNumbers[1000];
//set all elements to false in array
for ( unsignedint i = 2; i <= 1000; i++ )
{
primeNumbers[i] = true;
}
//step through array
for ( unsignedint i = 2; i <= 1000; i++ )
{
if ( primeNumbers[i] )
{
for ( int j = i + 1; j < 1000; j++ )
{
if ( j % i == 0 )
{
primeNumbers[j] = false;
}
}
}
}
for ( unsignedint i = 2; i <= 1000; i++ )
{
if ( primeNumbers[i] )
{
std::cout << i << " ";
}
}
std::cout << std::endl;
return 0;
}
Line 11 (and others) i <= 1000
this will access primeNumbers[i] with an out of range subscript. Remember array elements are numbered starting from 0, so valid subscripts would be 0 to 999.
Change the <= to < i <= 1000 to i < 1000
Also, rather than having the number 1000 appearing multiple times throughout the program, use a defined constant.