Just now, we have seen, how to check whether a given number m is prime or not. Let us modify this program to generate prime numbers within the range n1 and n2.

So, when m is prime, in place of displaying the message " The number is prime", let us print the prime number. If m is not prime, instead of displaying the message "The number is not prime", take the next number in the range. If these modifications are done to the program discussed in the previous section, then prime numbers within the range are generated. The modified program is shown below:

#include<stdio.h>

void main( )

{

int n, n1, n2, i, count, prime;

printf("Enter n1 and n2:\n");

scanf("%d%d",&n1,&n2);

count=0;

printf("Primes between %d to %d are: \n", n1, n2);

for (n=n1; n<=n2; n++)

{

prime =1; /* Assume m is prime */

for (i=2; i<=n/2; i++)

{

if(n%i == 0)

{

/* n is not prime */

prime =0;

break;

}

}

/* if m is not prime, take next m, */

if(prime == 0) continue;

/* print the prime number */

printf("%d",n);

count++; /* Update the counter */

}

printf("No. of primes = %d\n",count);

}

Enter n1 and n2:

2 9

count = 0

m=2 3 4 5 6 7 8 9

4 6 8 9

are not prime numbers and they are skipped

2 3 5 7

No. of primes = 4

**Procedure**: Assume m varies from n1 to n2. If m is prime let us display it. Otherwise, take the next number in the range and check for prime number. If it is prime, display it; otherwise, take the next number and repeat the procedure. Thus, all prime numbers are displayed in the range n1 to n2.So, when m is prime, in place of displaying the message " The number is prime", let us print the prime number. If m is not prime, instead of displaying the message "The number is not prime", take the next number in the range. If these modifications are done to the program discussed in the previous section, then prime numbers within the range are generated. The modified program is shown below:

#include<stdio.h>

void main( )

{

int n, n1, n2, i, count, prime;

printf("Enter n1 and n2:\n");

scanf("%d%d",&n1,&n2);

count=0;

printf("Primes between %d to %d are: \n", n1, n2);

for (n=n1; n<=n2; n++)

{

prime =1; /* Assume m is prime */

for (i=2; i<=n/2; i++)

{

if(n%i == 0)

{

/* n is not prime */

prime =0;

break;

}

}

/* if m is not prime, take next m, */

if(prime == 0) continue;

/* print the prime number */

printf("%d",n);

count++; /* Update the counter */

}

printf("No. of primes = %d\n",count);

}

### Tracing

**Input**Enter n1 and n2:

2 9

**Computations**count = 0

m=2 3 4 5 6 7 8 9

4 6 8 9

are not prime numbers and they are skipped

**Output**2 3 5 7

No. of primes = 4

## 0 comments:

## Post a Comment