This is a discussion on Please help me with this "prime checker" exercise! within the C++ Programming forums, part of the General Programming Boards category; Hi all guys, I'm stucking in this exercise, which tells me to write a C++ program to check whether a ...

Hi all guys,
I'm stucking in this exercise, which tells me to write a C++ program to check whether a number is prime. This is my code, I've debugged it and there are no errors or warnings. But when I enter 9, it said 9 is a prime!!! In general, whenever I enter a composite ODD number, it alwas considers it as a prime. If you find my mistakes in this code, please tell me so that I could finish this crazy exercise. Thank you very much!!!

Code:
```#include<stdio.h>

void main(void)
{
int n, i, r;
printf("Enter a number:");
scanf("%d", &n);
if(n==1) {
printf("This is neither a prime nor a composite number.");
}
for(i=2;i<=n;i++)
{
r=n%i;
if(r==0) {
printf("This is not a prime.");
break;
} else {
printf("This is a prime.");
break;
}
}
}```

2. Again, this is no C++ !

3. Originally Posted by blackhawk65
Hi all guys,
I'm stucking in this exercise, which tells me to write a C++ program to check whether a number is prime. This is my code, I've debugged it and there are no errors or warnings. But when I enter 9, it said 9 is a prime!!! In general, whenever I enter a composite ODD number, it alwas considers it as a prime. If you find my mistakes in this code, please tell me so that I could finish this crazy exercise. Thank you very much!!!

Code:
```#include<stdio.h>

void main(void)
{
int n, i, r;
printf("Enter a number:");
scanf("%d", &n);
if(n==1) {
printf("This is neither a prime nor a composite number.");
}
for(i=2;i<=n;i++)
{
r=n%i;
if(r==0) {
printf("This is not a prime.");
break;
} else {
printf("This is a prime.");
break;
}
}
}```
Your algorithm tries to determine if a number is prime too early (first iteration of the loop). Testing numbers up to (and including) sqrt(N) is a sufficient approach, BTW. Oh, and 'main' returns an 'int', not 'void'.

4. You must first get your thinking correct before you can get your code correct.
Can you explain in your own words, how to know whether a number is prime or not?