In: Computer Science
Develop and write a program in c/c++ that will find the first 100 primes (starting at 1) and write them to a file named "primes.dat".
CODE FOR THE FOLLOWING PROGRAM:-
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//Variables used in the program
int num,j;
// open a file in write mode.
ofstream fout;
fout.open("primes.dat");
//loops to check whether number is prime or not if it is prime write it on file
for(num=1;num<=100;num++){
for(j=2;j<num;j++){
if(num%j==0){
break;
}
}
if(j==num){
//Printing prime number to file primes.dat
fout<<num<<endl;
}
}
// close the opened file.
fout.close();
return 0;
}
SCREENSHOT OF THE CODE AND SAMPLE OUTPUT:-
SAMPLE OUTPUT:-
After you run the program you will see file named primes.dat in the folder where your .cpp file is stored.
Open the primes.dat file and you will see all the prime numbers between 1 to 100 in it.
HAPPY LEARNING