c - Please help me find error - program which shows prime numbers -


i learning c , me find error in program? retyped code book , still don't know mistake. tried use https://www.diffchecker.com/diff don't see logical difference. give up. me?

my code:

//ex7_9.c #include <stdio.h> #include <stdbool.h>  int main(void){      int num;     int limit;     int div;     bool isprime;      printf("please insert number: ");     while((scanf("%d", &limit) == 1) && limit > 0){         if(limit > 1)             printf("here prime numbers %d limit\n", limit);         else             printf("change limit - bigger one\n");          for(num=2; num <= limit; num++){             for(div=2, isprime=true; (div*div) <=num; div++){                  if(num % div ==0)                     isprime = false;                  if(isprime)                     printf("%d prime \n",num);              }         }     }      return 0; } 

proper code:

//ex7_9.c #include <stdio.h> #include <stdbool.h>  int main(void){      int limit;     int num;     int div;     bool numisprime;      printf("enter positive integer: ");     while (scanf("%d", &limit) == 1 && limit > 0){         if (limit > 1)             printf("here prime numbers through %d\n", limit);         else             printf("no primes.\n");         (num = 2; num <= limit; num++)         {             (div = 2, numisprime = true; (div * div) <= num; div++)                 if (num % div == 0)                     numisprime = false;             if (numisprime)                 printf("%d prime.\n", num);         }         printf("enter positive integer (q quit): ");     }     printf("done!\n");     return 0; } 

results code:

please insert number: 10 here prime numbers 10 limit 5 prime  7 prime  9 prime  

you added brackets on inner loop.

your code is

for(num=2; num <= limit; num++){     for(div=2, isprime = true; div * div <=num; div++){         if(num % div == 0)         {             isprime = false;         }         if(isprime)         {             printf("%d prime \n",num);         }     } } 

while original explicit brackets added is

for (num = 2; num <= limit; num++) {     (div = 2, numisprime = true; div * div <= num; div++)     {         if (num % div == 0)         {             numisprime = false;         }     }     if (numisprime)     {         printf("%d prime.\n", num);     } } 

your second if inside inner loop; in original outside.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -