Prime numbers are those positive numbers which are only divisible by 1 and the number itself. A simple logic can be written to check this like starting iteration with 2 to (number -1) and inside this we check if number is divisible. If it completes all iterations and found not divisible by any number in the range then it is a prime number.

``` 1  #define TRUE 1
2  #define FALSE 0
3  bool is_prime(unsigned int number)
4  {
5    unsigned int i;
6    for (i = 2; i < number; i++)
7    {
8      if((number%i) ==0)
9        return FALSE;
10    }
11    return TRUE;
12  }
13  ```

Print all prime numbers in a given range

``` 1
2  int main(int argc, char* argv[])
3  {
4    unsigned int index;
5    unsigned int range;
6    printf("Print Prime numbers till #");
7    scanf("%u", &range);
8    for(index = 1; index <= range; index++)
9    {
10      if(is_prime(index) != FALSE){
11        printf("%u,", index);
12      }
13    }
14    printf("\b.");
15    return 0;
16  }
17
18  Output:
19  Print Prime numbers till #50
20  1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47.
21  ```

Print first n-number of prime numbers

``` 1
2  int main(int argc, char* argv[])
3  {
4    unsigned int index;
5    unsigned int count;
6
7    printf("\nHow many prime no to print #");
8    scanf("%u", &count);
9    for(index = 1; count > 0; index++)
10    {
11      if(is_prime(index) != FALSE){
12        printf("%u,", index);
13        count--;
14      }
15    }
16    printf("\b.");
17    return 0;
18  }
19  Output:
20  How many prime no to print #10
21  1,2,3,5,7,11,13,17,19,23.
22  ```

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

0

Similar topics related to this section