1. ## for loop failure...

Why does my SECOND for loop (in RED) work as written, but fail when I change the values of the variables? Here's the simple program (to determine prime numbers):

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

int main (int argc, const char * argv[]) {

int p, d;
_Bool isPrime;

for ( p = 2; p <= 50; ++p ) {
isPrime = 1;
for ( d=2; d<p; ++d)
if (p % d == 0)
isPrime = 0;
if (isPrime)
printf("%i is a prime number.\n",p);
}

return 0;}```
The issue is this: If the SECOND for loop is written as
Code:
`for ( d=1; d<50; ++d)`
the program exits without printing anything.

But this for loop works perfectly:

Code:
`for ( d=2; d<p; ++d)`
So my questions are:

1) Why can't looping begin with d = 1 ? Why does it need to begin with d = 2 ?

2) And why can't the limiting expression be d<50 (or some other number)? Why must it be p ?

I'm a noob, so the issue isn't obvious. I'm posting here after hours of googling turned up nothing.

2. 1) If you start with d=1, then any number will be divisible by 1. Therefore your test for prime will not be valid.
2) If you go above and beyond the tested "prime" number, you will eventually always find a number that divides into it. The number itself for example. So no number will ever be flagged as prime.

3. Thanks for the quick, clear response! Now it seems very clear and obvious. But without your explanation, I'd still be banging my head against the wall.

4. Also, note that you don't need to iterate until p to figure out if it is prime. If you go until sqrt(p) and you don't find any divisors then there are no prime divisors which means the number is prime.

5. Originally Posted by claudiu
Also, note that you don't need to iterate until p to figure out if it is prime. If you go until sqrt(p) and you don't find any divisors then there are no prime divisors which means the number is prime.
Another quick check if you are working with ints is to check bit 0 ... bit 0 can never be 0 in a prime number (since that would mean it's and even number and thus divisible by 2)...

6. Thanks, claudiu and Tater, appreciate your input -- though I was less interested in that clichéd prime numbers exercise than in why my for loop didn't seem to be working.