Here's the problem-
Write a C++ program that prompts the user to input a positive integer then output the number and a message indicating whether the number is a prime number.
I found this solution....
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cout<<" Enter a number to find if its a prime number "<<endl;
cin>>n;
bool a =true;
for(int i=2;i<sqrt(n);i++)
{
if(n%i==0)
{
a=false;
break;
}
}
if(a==false)
cout<<n<<" is not a prime number"<<endl;
else
cout<<n<<" is a prime number"<<endl;
}
my question is how do i edit this program to take out bool, for and break? I ran the program and it works but my professor hasn't covered those completely.
I don't program in C but i'm pretty good at extrapolating code functions from their appearance and syntax, In any case, since this is an assignment I doubt they want you using any outside libraries or function calls (methods), etc to solve it, so you're going to be stuck with at least one loop.
I don't know if theres a C equivalent to the java "return;" command, but there probably is; I'd imagine its a standard in programming languages
You can eliminate the boolean flag by using the (cout<<n<<" is not a prime number"<<endl;) line where you were setting the boolean to false and immediately end the program at that point.
This way, if the program finishes the loop without finding a zero modulus (n%i==0) you KNOW the number is prime, so you don't have to check a flag.
This would eliminate the need for the second if/else statement.
P.S. I recommend attempting to write your own solutions. Don't try to "find" ready made answers, you dont learn as much