Loading, please wait...

A to Z Full Forms and Acronyms

How to Print Prime Number in C++?

Aug 19, 2019 C++, 1262 Views
To display the prime numbers in a given range

Let's create a program to display the prime number in a given range:

#include <iostream>
using namespace std;
int main()
{
    int low, high, i, flag;
    cout << "Enter two numbers: ";
    cin >> low >> high;
    cout << "Prime numbers between " << low << " and " << high << " are: ";
    while (low < high)
    {
        flag = 0;
        for(i = 2; i <= low/2; ++i)
        {
            if(low % i == 0)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 0)
            cout << low << " ";
        ++low;
    }
    return 0;
}

Output:

Enter two numbers: 5 50
Prime numbers between 5 and 50 are: 5 7 11 13 17 19 23 29 31 37 41 43 47

Parameters used in the Program

  • #include<iostream> - It the compiler to include iostream file. This file contains predefined input/output functions that we can use in our program.
  • using namespace std - All the elements of the standard C++ library are declared within what is called a namespace. In this case the namespace with the name std. We put this line in to declare that we will make use of the functionality offered in the namespace std. This line of code is used very frequently in C++ programs that use the standard library. You will see that we will make use of it in most of the source code included in these tutorials.
  • int main() - it is the main function of our program and the execution of the program begins with this function, the int here is the return type which indicates to the compiler that this function will return an integer value. That is the main reason we have a return 0 statement at the end of the main function.
  • cout<< - The cout object belongs to the iostream file and the purpose of this object is to display the content between double quotes as it is on the screen and to display the value of variables on the screen.
A to Z Full Forms and Acronyms

Related Article