C Program to Print PRIME Numbers in a Given Range

Prime number have only two factors, 1 and the number itself. The given program in other article shows the code for prime numbers, this program reduces the number of iterations in the for loop to half.

This program is exactly same to that code but change in the number of iterations in the for loop.

The flowchart for prime numbers gives you the flow of the execution.

The better and more optimized version of java code given in the link.

#include<stdio.h>
int main ()
{
    int i, prime, up, low, n;
    printf ("ENTER THE LOWER LIMIT : ");
    scanf ("%d", &low);
    printf ("ENTER THE UPPER LIMIT : ");
    scanf ("%d", &up);
    if(low>=2)
    {
        printf ("PRIME NUMBERS ARE : ");
        for (n = low + 1; n < up; n++)
        {
            prime = 1;
            for (i = 2; i < n/2; i++)
                if (n % i == 0)
                {
                    prime = 0;
                    break;
                }
            if (prime)
                printf ("\t %d", n);
        }
    }
    else
    {
        printf("Enter lower number must be greater than 1");
    }
}

In the above program, the inner loop repeats only n/2 number of times.

Output:

ENTER THE LOWER LIMIT : 2
ENTER THE UPPER LIMIT : 100
PRIME NUMBERS ARE :      3       4       5       7       11      13      17      19      23      29      31      37      41      43      47      53      59      61      67      71      73      79      83      89      97

Leave a Reply

Your email address will not be published.