C Program to generate prime numbers between two numbers | prime numbers between n1 and n2

Spread the love
This article is one of the article in Series of Prime number generation programs. In my previous articles i discussed about
What is prime Number and C program to Check given number is Prime or Not,
Check given Number is Prime or not Using Square Root(sqrt) Function.(Efficient way).
Now we will discuss about c program to generate prime numbers between two numbers.

Description :

This program accept two integers from user and and generates all prime numbers between those two Numbers. here i am using two loops one is Outer loop and second one is Inner loop. outer loop will starts with n1( first number of user) and ends with n2 (user’s second number ). Inner loop is normal prime number logic loop starts with 2 and ends with n/2 (you can use sqrt(n) ).

Program :

  1. #include<stdio.h>
  2. void main()
  3. {
  4.         int i,j,cnt,n1,n2;
  5.         printf(“Enter two Numbers : “);
  6.         scanf(“%d%d”,&n1,&n2);
  7.         // n2 must be grater than n1, so check it first
  8.         if(n1 > n2)
  9.         {
  10.                 printf(“n2 must be greater than n1 n);
  11.                 return;
  12.         }
  13.         printf(“prime Numbers between %d and %d are : “,n1,n2);
  14.         for(i=n1; i<=n2; i++)
  15.         {
  16.                 // use one count variable, make it as 0 for every iteration
  17.                 cnt = 0;
  18.                 // loop for checking number is prime or not
  19.                 for(j=2; j<=i/2; j++)
  20.                 {
  21.                         if(i%== 0)
  22.                         {
  23.                                 cnt++;
  24.                                 break;
  25.                         }
  26.                 }
  27.                 if(cnt == 0)
  28.                 printf(“%d “,i);
  29.         }
  30.         printf(n);
  31.         return ;
  32. }

Output :

Output of Prime number between two numbers program

Related C programs :

Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer and an Open Source enthusiast, Presently working as a Software Engineer. Apart from that, I love to explore new technologies and things.

You may also like...

Leave a Reply