# why the prime numbers cant be displayed?

This is a discussion on why the prime numbers cant be displayed? within the C Programming forums, part of the General Programming Boards category; hi,i am using dev c++. here is my code. Code: #include <stdio.h> #include <stdlib.h> int is_prime(int n); void main() { ...

1. ## why the prime numbers cant be displayed?

hi,i am using dev c++.
here is my code.

Code:
```#include <stdio.h>
#include <stdlib.h>
int is_prime(int n);

void main()
{
int x;
printf("How many prime numbers? ");
scanf("%d", &x);
printf("\n %d prime numbers: ",x);

int j=1;
int i=1;
for(i=1;i<=x;i++)
{
printf("\n %d :",i);
for(j=1;is_prime(j)==0;j++)
{
if(is_prime(j)==1)
printf("%d",j);
}

}

system("PAUSE");

}
//function definition
int is_prime(int n)
{
int k, limit;
if(n==1)
return 0;
if(n==2)
return 1;
if(n%2==0)
return 0;
limit =n/2;
for(k=3;k<=limit;k+=2)
if(n%k==0)
return 0;
return 1;
}```

2. well one thing to look at is for loop is never executed in your is_prime function

3. Originally Posted by rogster001
well one thing to look at is for loop is never executed in your is_prime function
No, it does.
it does not print prime numbers because
Code:
` for(j=1;is_prime(j)==0;j++)`
the test condition is wrong. 0 means it is NOT prime. So it does not get executed at all.If the inner for loop is for checking whether a number is prime or not fails, you still increment 'i' thinking that it has found a prime number, when in fact it hasn't. If j is always initialized to 1 in your j for loop and a condition in your function is_prime(n)
Code:
```if(n==1)
return 0;```
then it naturally fails every time from i to x.

All you need is:
Code:
```for(j=1; i <= x;j++)
{
if(is_prime(j)==1) {
printf("\n%d",j);
i++;
}
}```

4. thz, your explanation helps me much^^

5. BTW, you can speed up your program by changing:
Code:
`limit =n/2;`
to:
Code:
`limit = sqrt( n ) + 1;`