#include <iostream>
#include <fstream>
usingnamespace std;
int main(int argc, constchar * argv[])
{
//tell user what program is doing
cout << "This program stores all prime numbers from 1 to 100 in a file." << endl;
//declare and open an output file for writing to
ofstream outputFile;
outputFile.open("primeNumbers.txt");
//for loop to go through every number up to 100
for (int i = 1; i <= 100; i++)
{
int ans = 1;
//for loop to determine if prime
for (int x = 2;i <= i/2; x++)
{
//if statement determines a not prime number
if (i % x == 0)
ans = 0;
//else it is prime
else
//writes to file the prime number
outputFile << i << endl;
}
}
//closes file
outputFile.close();
return 0;
}
#include <iostream>
#include <fstream>
usingnamespace std;
int main(int argc, constchar * argv[])
{
//tell user what program is doing
cout << "This program stores all prime numbers from 1 to 100 in a file." << endl;
ofstream outputFile; //declare and open an output file for writing to
outputFile.open("primeNumbers.txt");
if(outputFile.is_open()) //You should check weather file opened or not
{
for (int i = 1; i <= 100; i++) //for loop to go through every number up to 100
{
int ans = 1;
for(int x=2;x<=i/2;++i)
{
if(i%x==0)
{
break; //If divide by any other than 1/itself then break loop
}
else
{
cout<<i<<" "; //write on Console
outputFile<<i<<" "; //write on file
}
}
}
}
outputFile.close(); //closes file
return 0;
}
I just tried this code, and it seems to be displaying just the odd numbers from 5 to 100
That's because you're outputting after each integer test. You have to iterate through the entire second for loop before you know if the number you are testing is prime or not, so the output code should be outside of the second for loop.
#include <iostream>
#include <fstream>
usingnamespace std;
int main(int argc, constchar * argv[])
{
//tell user what program is doing
cout << "This program stores all prime numbers from 1 to 100 in a file." << endl;
ofstream outputFile;
outputFile.open("primeNumbers.txt");
if(outputFile.is_open())
{
for (int i = 1; i <= 100; i++)
{
bool prime = true;
for(int x=2;x<=i/2;x++)
{
if(i%x==0)
{
prime = false;
}
}
if (prime == true)
{
outputFile << i;
cout << i << " ";
}
}
}
outputFile.close(); //closes file
return 0;
}
#include "stdafx.h"
#include "conio.h"
#include "iostream"
#include <fstream>
usingnamespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//tell user what program is doing
cout << "This program stores all prime numbers from 1 to 100 in a file." << endl;
ofstream outputFile; //declare and open an output file for writing to
outputFile.open("primeNumbers.txt");
if(outputFile.is_open()) //You should check weather file opened or not
{
for (int i = 1; i <= 100; i++)
{
int ans = 1;
int x;
//for loop to determine if prime
for (x = 2;x <= i/2; x++)
{
//if statement determines a not prime number
if (i % x == 0)
break;
}
if(x>i/2)
{
outputFile <<i<<" ";
cout<<"\t"<<i;
}
}
}
outputFile.close(); //closes file
getch();
return 0;
}