Hi,
For my class, I needed to write program that asks a use for a number, then tells them whether or not that number is prime.
It is supposed to run the program again and again until the user enters 0 as a number, then it exits.
We never talked about running programs again, and I'm really not sure how to go about it. I *could* write a while(x=!0) loop, but that would require duplicative code, since the main loop would have to exist twice.
So the only thing I can think of is to use a label, and a goto. But I have heard through my quick search on the net to avoid this method?
What else would work?
What I've got does work, but maybe there could be a better way.
Here is my code (sorry if the formatting isn't good - just trying to get my idea down quickly):
For my class, I needed to write program that asks a use for a number, then tells them whether or not that number is prime.
It is supposed to run the program again and again until the user enters 0 as a number, then it exits.
We never talked about running programs again, and I'm really not sure how to go about it. I *could* write a while(x=!0) loop, but that would require duplicative code, since the main loop would have to exist twice.
So the only thing I can think of is to use a label, and a goto. But I have heard through my quick search on the net to avoid this method?
What else would work?
What I've got does work, but maybe there could be a better way.
Here is my code (sorry if the formatting isn't good - just trying to get my idea down quickly):
Code:
#include <iostream>
using namespace std;
int main()
{
cout << "Prime Number Tester" << endl;
cout << "-------------------" << endl;
Beginning: // label used to repeat program until 0 is entered
int x; // the number entered by the user
int y = 2; // variable used for loop to test if prime (y ranges from 2 to 1 less than x)
// ask user for a number
cout << "Please enter a number: ";
cin >> x;
cout << endl;
// main loop. Once x = 0 (or less) program ends.
while(x>0)
{
// divide X by all numbers 1-x to see if it is prime
while(y<=(x-1))
{
if(x%y == 0)
{ cout << x << " is not Prime" << endl << endl;
break;
}
y++;
// if y makes it to x without being evenly divisble, x is prime.
if(y==x)
{ cout << x << " is Prime" << endl << endl;
}
}
goto Beginning;
}
cout << "Thank you!" << endl;
return 0;
}