I need to write a program that asks user input of a number,
checks if it is prime, and displays a message if it is prime and saves it to a file.
I also need it to display a message if it is not prime and not save it to a file.
I was able to get the file created but its blank because no matter what number the user enters, it says it is not prime.
How do I get the condition to work to test if the number is prime or not?
What i tried didn't work.
I must then use my isPrime function to store all the prime numbers from 1-100 in a file. Not sure how to go about this.
Should I ask the user to enter all prime numbers 1-100 and store the results in an array? I am not familiar with arrays so if there is an easier way I'd love to know....
#include <iostream>
#include <fstream>
usingnamespace std;
bool isPrime(int); //Function prototype
bool isPrime(int number) //Passes the variable to function isPrime
{
//Array variables
constint PRIME_NUMBERS = 25; //Number of Prime numbers
int numbers[PRIME_NUMBERS]; //Each user input
int count; //Loop counter
//Variables
ofstream outputFile;
bool status;
int i=2;
while(i<=number-1)
{
if(number%i==0)
{
status=false;
cout << number << " is not a prime number." << endl;
break;
}
i++;
}
if(i==number)
{
status=true;
//Opens file for output
outputFile.open("PrimeNumbers.txt");
cout << number << " is a prime number.\n"; //Returns true value
//Input the prime numbers (1-100)
for (count = 0; count < PRIME_NUMBERS; count++)
{
cout << "\nGreat. Now, please enter all prime numbers (1-100): \n"
<< (count + 1) << ": ";
cin >> numbers[count];
}
//Display contents of array
cout << "The numbers you entered are: ";
for (count = 0; count < PRIME_NUMBERS; count++)
cout << " " << numbers[count];
cout << endl;
//Write contents of array to a file
outputFile << "List of prime numbers: \n";
for (count = 0; count < PRIME_NUMBERS; count++)
outputFile << numbers[count] << endl;
cout << "This data has been saved to a file.\n";
//Closes the file.
outputFile.close();
}
return status;
}
int main()
{
//Local variables
int number;
bool status;
//Asks for user input
cout << "\nPlease enter a number to find if it is prime: \n";
cin >> number; //Stores user input
//Calls isPrime function
(isPrime(number));
return 0;
}