# Print prime numbers in C++

In this tutorial, we will get to know how to **print prime numbers in C++**. We will take a number limit from the user and display all the prime numbers less than or equal to that number. Also, we will see a C++ program that displays the primes numbers within a given maximum limit. Here, you will learn about prime numbers, the logic to find prime numbers and a C++ program which implements this logic.

## The logic for finding prime numbers

A prime number is a number that is completely divisible by 1 and itself only. Any other number cannot divide a prime number completely. For example –

The number 3 is divisible by 1 and 3 only. So, it is a prime number.

To find it, we can perform a divisibility test of that number with all the numbers greater than 1 up to that number. If at any time, the divisibility test returns success, then the number is not a prime number.

bool check_prime(int num) { bool prime=true; for(int i=2;i<=num/2;i++) { if(num%i==0) { prime=false; break; } } return prime; }

This function returns a boolean value. It takes a number as parameter and stores it in variable *‘num’*. And checks the divisibility of that number with all the numbers from 2 to (num/2). It calculates the remainder when the *‘num’* is divided by loop control variable *‘i’*. If the remainder is 0, the *‘prime’* variable is assigned to false. If for all the values of *‘i’*, there is a remainder, then the function returns true to the calling function.

## C++ program to print prime numbers

Here, we will see a C++ program that displays all the prime numbers which are less or equal to the maximum limit. The program uses the user-defined function which we discussed above.

#include <iostream> using namespace std; bool check_prime(int); int main() { bool prime; int max; cout<<"ENTER THE MAXIMUM NUMBER : "; cin>>max; if(max<2) cout<<"\nNUMBER SHOULD BE GREATER THAN 2"; for(int i=2;i<=max;++i) { prime=check_prime(i); if(prime) cout<<i<<" "; } return 0; } bool check_prime(int num) { bool prime=true; for(int i=2;i<=num/2;i++) { if(num%i==0) { prime=false; break; } } return prime; }

The *main()* function takes the maximum limit form the user. It calls the *check_prime()* function and passes this limit to this function. The *check_prime()* function returns true if it is a prime number. Otherwise, false is returned to the calling *main()* function.

#### C++ program output

The above program generates all the prime numbers within the limit. The output of the program is –

[email protected]:~/cpp$ g++ prime.cpp [email protected]:~/cpp$ ./a.out ENTER THE MAXIMUM NUMBER : 100 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 [email protected]:~/cpp$

In the execution, the maximum limit is 100. So, the program generates the number which is less than or equal to 100.

Thank you for reading this tutorial. I hope it helps you.

Also read:

## Leave a Reply