Home »
C++ programs »
C++ Most popular & searched programs
C++ program to display prime numbers
Input the value of N and then print the primer numbers between 1 to N using C++ program.
[Last updated : February 28, 2023]
C++ - Printing prime numbers between 1 to N
In this program, we will read the value of N (range of the numbers) and print the all prime numbers from 2 to N.
To check prime numbers, we are creating a user defined function isPrime() that will take an integer number and return 1 if number is prime and 0 if number is not prime.
Program to display prime numbers in C++
#include <iostream>
using namespace std;
//function to check prime numbers
int isPrime(int num);
int main()
{
int i;
int n; //to store, maximum range
cout << "Enter maximum range (n): ";
cin >> n;
//print prime numbers from 2 to n
cout << "Prime numbers:" << endl;
for (i = 2; i < n; i++) {
if (isPrime(i))
cout << i << " ";
}
cout << endl;
return 0;
}
//function definition
int isPrime(int num)
{
int cnt;
int prime = 1;
for (cnt = 2; cnt <= (num / 2); cnt++) {
if (num % cnt == 0) {
prime = 0;
break;
}
}
return prime;
}
Output
Enter maximum range (n): 100
Prime numbers:
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