Hello. For my class I had to write a program that asks for user input of a number. It then checks to see if this number is prime or not. If it is not prime, the program says so and will close.
If it is prime, however, the program will tell you and then go on to ask the user to enter all prime numbers from 1-100. I used an array of 25 elements to store all possible combinations of prime numbers from 1-100. It then saves these elements to a file titled PrimeNumbers.txt
This part of the program is working fine. However, I realized that there is no error checking in the second part of my program. The first part will check if the number is prime or not but the second part does not. Technically you could enter 1, 1, 1, etc... and it would save them as if they were prime.
I need a way to check if the numbers are prime in the second part of my program and I need to be able to break out of the array if the number is not prime and ask the user to start over again.
But I do not know how to go about doing this.
I am also very inexperienced with programming so a detailed description would be much appreciated!
Thank you in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int); //Function prototype
bool isPrime(int number) //Passes the variable to function isPrime
{
//Array variables
const int 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;
}
|