I've been trying to implement the Eratosthenes sieve in C++. I am using the Dev C++ 5.11 compiler and every time I run my code, the compiler crashes. For a smaller array value (n = 10000), the program runs successfully, but prints garbage values in the text file (Please find image attached). I am an amateur in programming and have been working over this issue for over a day now. Would be glad for any help. Thanks for your time! :)
#include <iostream>
using namespace std;
#include <fstream>
int main(){
ofstream myfile("Prime.txt");
int n = 1000000;
int prime[n] = {0};
for (int i = 2; i <= n; i++){
for (int j = i*i; j <= n; j+=i){
prime[j - 1] = 1;
}
}
for (int i = 2; i <= n; i++){
//cout<<prime[i-1]<<endl;
if (prime[i - 1] == 0)
myfile<<i<<" ";
}
myfile.close();
return 0;
}