Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Saturday 13 July 2013

Generate Prime Numbers Within a Range Of Numbers C Program

Hello Guys
In this post, I will explain the C Program, how to generate Prime Numbers within a range of numbers. prime number (or a prime) is a natural number (i.e. 1, 2, 3, 4, 5, 6, etc.) greater than 1 that has no positive divisors other than 1 and itself.natural number  is called a prime or a prime number if it has exactly two positive divisors, '1' and the number itself.

Now I will explain how to find out all the prime numbers within a range of numbers, which will be taken as an input from the user. The code is self-explained and quite easy.

First, we take the upper and lower limit range as an input from the user. Then in the main logic begins. We initiate a loop variable 'i' from the lower limit till the upper limit. Inside that, we use a temporary variable 'k' which takes the value same as 'i'. Now for every 'k' another loop runs, in which we check all numbers from 2 to k/2 (As no number can have any divisor greater than [number/2] ) and see that if any remainder comes or not. If any remainder comes, flag variable becomes false or 0. But in those cases where the flag variable remains 1, that number is a Prime number and is printed on the screen.

Generate Prime Numbers Within a Range Of Numbers C Program:


/* Double-Click To Select Code */

#include <stdio.h>
#include <conio.h>

int main(void)
{
 int m,n,i,j,k,flag;
 clrscr();

 printf("\nEnter The Lower Limit: ");
 scanf("%d",&m);
 printf("\nEnter The Upper Limit: ");
 scanf("%d",&n);

 printf("\nPrime Numbers Between %d & %d Are:\n",m,n);
 for(i=m ; i<=n ; i++)
 {
  k=i;
  flag=1;
  for(j=2 ; (j<=k/2)&&flag ; j++)
  {
   if(k%j==0)
   flag=0;
  }

  if(flag)
  printf("%3d \n",i);
 }

 getch();
 return 0;
}


Program Output:


Generate Prime Numbers Within a Range Of Numbers C Program


Please Comment If You Liked The Post.



Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: