#include %26lt;stdio.h%26gt;
main()
{
int n,i,j;
printf("\nInput n:");
scanf("%d",%26amp;n);
for (i=3;i%26lt;=n;i++)
{ int bool=0;
for (j=2;j%26lt;i;j++)
{
if ((i%j)!=0)
bool=1;
else
break;
}
if (bool=1) printf ("\nPrime number:%d",i);
}
}
Sth wrong w/ this code !!
Help me solve this C program finding prime numbers %26lt;=n,please !!?
#include%26lt;stdio.h%26gt;
#include%26lt;conio.h%26gt;
void main()
{
int count,i=1;
int a;
clrscr();
while(i%26lt;=500)
{
count=0;
a=1;
while(a%26lt;=i)
{
if(i%a==0)
count++;
a++;
}
if(count==2)
printf("%d\t",i);
i++;
}
getch();
}
just type this program and save as .c file
u will able to print prime numbers between 1 to 500
if u want more just replace 500 with urs range
Reply:There are a few glitches in your code.
for starters the main() method has no return type. It's default would be void, but in this case I assume you'd require a return type of int as a minimum; for example:
int main() {
Your first loop to me seems right but I suspect it should read:
for (i = 2; i %26lt;=n; i++) {
It would then be usual to provide a boolean of true, or in your case bool = 1
By the way, speaking of that bool, why not declare it up top along with the ints; i.e.:
int n, i, j, bool;
You second for loop needs a minor amendment:
for(j = 2; j %26lt;= i; j++) {
If you change that then if i == j you would continue
Otherwise if( i%j==0) bool = 0; as this produces a false statement.
Thus your if((i%j) != 0) bool = 1; technically needs modification.
I'd be tempted to use the %26lt;iostream%26gt; rather than %26lt;Stdio%26gt; as well but I guess that is a matter of preference because if you use %26lt;iostream%26gt; you get the odd whitespace issues which require bits like std::cin and std::cout etcetera.
Just in case I missed something there here is how I'd write your problem if I was doing it. Perhaps something here will jog your mind to allow you to adapt your style.
#include%26lt;iostream%26gt;
int main()
{
int n , isprime;
std::cout%26lt;%26lt;"Enter number :";
std::cin%26gt;%26gt;n;
for( int i = 2 ; i %26lt;= n ; i++)
{
isprime = 1;
for( int j = 2 ; j %26lt;= i ; j++)
{
if( i == j)
continue;
else if( i % j == 0)
isprime = 0;
}
if(isprime)
std::cout%26lt;%26lt;i%26lt;%26lt;" ";
}
}
pokemon cards
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment