Read a positive integer and then displays all the prime numbers smaller than or equal to that number. - C Operator

C examples for Operator:Arithmetic Operator

Description

Read a positive integer and then displays all the prime numbers smaller than or equal to that number.

Demo Code

#include <stdio.h>  
#include <stdbool.h>  
int main(void)  
{  /*from   w w  w  .  j a va 2s. c o  m*/

    int limit;  
    int num;  
    int div;  
    bool numIsPrime;  // use int if stdbool.h not available  
      
    printf("Enter a positive integer: ");  
    while (scanf("%d", &limit) == 1 && limit > 0)  
    {  
        if (limit > 1)  
            printf("Here are the prime numbers up through %d\n", limit);  
        else  
            printf("No primes.\n");  
            
        for (num = 2; num <= limit; num++)  
        {   
              for (div = 2, numIsPrime = true; (div * div) <= num; div++)  
                 if (num % div == 0)  
                     numIsPrime = false;  
              if (numIsPrime)  
                 printf("%d is prime.\n", num);  
        }  
        printf("Enter a positive integer (q to quit): ");  
    }  
    printf("from book 2s.com!\n");  
    return 0;  
}

Result


Related Tutorials