in C Write a void function that uses two nested for loops an
(in C++)
Write a void function that uses two nested for loops and the mudulus (%) operator to detect and print to a specified output file, the first n prime integers. Recall that a prime number is a number that is evenly divisible only by 1 and itself. Hint: the funciton prototype is: primeGen(int n, ostream& file) ; and a precondition is that file is defined.
** Below is what I have so far and it\'s really just not printing anything at all to my output file (file.txt) while my input file contains the numbers 1 through 10. I fyou could please rewrite my code so that it works I\'d be very appreciative. I\'m at a total loss for what to do.
#include<iostream>
#include<fstream>
#include<cmath>
#include<string>
using namespace std;
void primeGen(int n, ofstream& file);
int main()
{
ifstream infile(\"d:\\\\primeGen.txt\");
if (infile.fail())
{
cerr << \"error opening primeGen.txt\";
exit(-1);
}
ofstream output;
output.open(\"d:\\\\file.txt\");
if (output.fail())
{
cerr << \"error opening file.txt\";
exit(-1);
}
while (!infile.eof())
{
int number;
infile >> number;
primeGen(number, output);
}
infile.close();
output.close();
return 0;
}
void primeGen(int n, ofstream& file)
{
int x, y;
bool isPrime;
for (x = 1; x <= n; n++)
isPrime = true;
for (y=2; y<=n;n++)
if (!(x%y))
{
isPrime = false;
}
if (isPrime)
file << x << endl;
}
Solution
// C++ code find prime numbers and output to file
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
#include <stdlib.h>
using namespace std;
void primeGen(int n, ofstream& file);
int main()
{
ifstream infile(\"d:\\\\primeGen.txt\");
if (infile.fail())
{
cout << \"error opening primeGen.txt\";
exit(-1);
}
ofstream output;
output.open(\"d:\\\\file.txt\");
if (output.fail())
{
cout << \"error opening file.txt\";
exit(-1);
}
while (!infile.eof())
{
int number;
infile >> number;
primeGen(number, output);
}
infile.close();
output.close();
return 0;
}
void primeGen(int n, ofstream& file)
{
int i,j;
int countPrime = 0;
int flag;
for(i=2;i>0;++i)
{
for(j=2;j<=i/2;++j)
{
if(i%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
file <<i << \" \";
countPrime++;
}
flag=0;
if(countPrime==n)
break;
}
file << \"\ \";
}
/*
primeGen.txt
1
2
3
4
5
6
7
8
9
10
file.txt
2
2 3
2 3 5
2 3 5 7
2 3 5 7 11
2 3 5 7 11 13
2 3 5 7 11 13 17
2 3 5 7 11 13 17 19
2 3 5 7 11 13 17 19 23
2 3 5 7 11 13 17 19 23 29
*/


