Sunday, March 13, 2011

C program to print prime numbers in a given range

Program
#include <stdio.h>

int main()
{
  int a,b,num,n,i;

  printf("\nEnter the number range (a b) (a > 1 and b > 1): ");
  scanf("%d %d",&a,&b);

  n=0;
  for(num=a;num<=b;num++)
    {
      for(i=1;i<=num/2;i++)
 {
   if (num%i == 0 && i != 1 && num != 2 && num != 3)
     break;
   else
     {
       if (i == num/2)
  {
    printf("\n%d is a prime number.\n",num);
    n=n+1;
  }
       continue;
     }
 }
    }
  
  if (n == 0) printf("\nNo prime numbers in the range %d - %d\n",a,b);
  else printf("\n%d prime numbers in the range %d - %d\n",n,a,b);

  return 0;
}
Compilation, Run and Output
[sreedhar@manchu2 cprograms]$ gcc prime_range.c -o prime_range
[sreedhar@manchu2 cprograms]$ ./prime_range 

Enter the number range (a b) (a > 1 and b > 1): 2 50

2 is a prime number.

3 is a prime number.

5 is a prime number.

7 is a prime number.

11 is a prime number.

13 is a prime number.

17 is a prime number.

19 is a prime number.

23 is a prime number.

29 is a prime number.

31 is a prime number.

37 is a prime number.

41 is a prime number.

43 is a prime number.

47 is a prime number.

15 prime numbers in the range 2 - 50
[sreedhar@manchu2 cprograms]$

No comments:

PBS Script Generator: Interdependent dropdown/select menus in Javascript

PBS SCRIPT GENERATOR
SH/BASH TCSH/CSH
Begin End Abort

About Me

LA, CA, United States
Here I write about the battles that have been going on in my mind. It's pretty much a scribble.

Sreedhar Manchu

Sreedhar Manchu
Higher Education: Not a simple life anymore