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

Spread the love
prime-numbers-between-two-numbers-in-c
In today’s article, We are going to write a program to find all prime numbers between two numbers in c programming Language.
This article is one of the articles in the 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.

 

The prime numbers between two numbers in c Program Description :

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

The prime numbers between two numbers in C 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.  
  14.         printf(“prime Numbers between %d and %d are : “,n1,n2);
  15.         for(i=n1; i<=n2; i++)
  16.         {
  17.                 // use one count variable, make it as 0 for every iteration
  18.                 cnt = 0;
  19.                 // loop for checking number is prime or not
  20.                 for(j=2; j<=i/2; j++)
  21.                 {
  22.                         if(i%== 0)
  23.                         {
  24.                                 cnt++;
  25.                                 break;
  26.                         }
  27.                 }
  28.                 if(cnt == 0)
  29.                 printf(“%d “,i);
  30.         }
  31.  
  32.         printf(“\n);
  33.         return ;
  34. }

Program Output :

prime-number-between-two-numbers-in-c
Output of Prime number between two numbers program

Related C programs :

Venkat

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

2 Responses

  1. […] C Program to Print Prime Numbers between Two numbers […]

  2. […] C Program to Print Prime Numbers between Two numbers […]

Leave a Reply