Print Prime Numbers Between Two Integers in C++

Computations and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. Well, prime numbers are very well known in the mathematical world. Therefore today we’re going to write a program to print Prime Numbers Between Two Integers in C++.

 

What Are Prime Numbers?

 

  • In a simplistic language, prime numbers are the natural numbers greater than 1, that can either be divided by itself or 1.

 

  • That means there are only two factors of a prime number, i.e 1 or the number itself.

 

  • 2, 3, 5, 7, 11, 13, 17, 19, etc are examples of prime numbers below 20.

 

What’s The Approach? 

 

We’ll take range as input, with the help of a for loop we’ll traverse the given input range.

 

In the Flag, the variable set the value as 1.

 

Next in another for loop, we’ll use modulo operation. On the iterating number, i from the first for loop starting with 2 and pre-increment of 1 with each iteration till we reach i/2.

 

If the modulo operation returns 1 the number is prime and we’ll print it. However, if it returns 0 then the number is not prime and won’t print it.

 

Also Read:  Print Armstrong Numbers Between Two Integers in Java

 

C++ Program To Print Prime Numbers Between Two Integers

 

Input:

a=2, b=20

 

Output:

3 5 7 11 13 17 19

 

// C++ program to find the prime numbers
// Between Two Integers

#include <bits/stdc++.h>
using namespace std;

int main()
{
    // Declare the variables
    int a, b, i, j, flag;
   a=2;//Upper Range
  
   b=20;//Lower Range
    // Print display message
    cout << "\nPrime numbers between "
        << a << " and " << b << " are: ";

    // Traverse each number in the interval
    // with the help of for loop
    for (i = a; i <= b; i++) {
        // Skip 0 and 1 as they are
        // neither prime nor composite
        if (i == 1 || i == 0)
            continue;

        // flag variable to tell
        // if i is prime or not
        flag = 1;

        for (j = 2; j <= i / 2; ++j) {
            if (i % j == 0) {
                flag = 0;
                break;
            }
        }

        // flag = 1 means i is prime
        // and flag = 0 means i is not prime
        if (flag == 1)
            cout << i << " ";
    }

    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published.