User input to find prime number

I am having trouble with this code. It is supposed to read a number that is inputted by the user, then tell the user whether that one number is prime or not. This code only shows that the number is prime no matter what number it is. Please help, thanks :)

#include <iostream>
#include <string>
using namespace std;
int main () {
//prompt user to enter a number greater than zero
int number;
bool prime;

cout << "\n";
cout << "Please enter a number greater than zero to check if it is prime: \n";
cout << "\n";
cin >> number;
cout << "\n";

for(int i = 3; i <= number; i++){
prime = true;
for(int n = 2; n <= i - 1; n++){
if(i % n == 0) {
prime = false;
}
}

//it only prints number is prime
if (prime) {
cout << number << " is prime! \n \n";
}
else {
cout << number << " is not prime :( \n \n";
}
Please use code tags. http://www.cplusplus.com/articles/jEywvCM9/
You can edit your post, highlight your code and click the <> button on the right.

1
2
3
4
5
6
7
8
for(int i = 3; i <= number; i++) {
    prime = true;
    for(int n = 2; n <= i - 1; n++) {
        if(i % n == 0) {
            prime = false; 
        }
    }
}

You were missing a curly brace for your inner for-loop.

This code only shows that the number is prime no matter what number it is.

That's because on every iteration you set prime to true.
Last edited on
Topic archived. No new replies allowed.