Home » C++ programs » C++ Most popular & searched programs

C++ program to display prime numbers

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 i;
	int prime=1;
	
	for(i=2;i<(num/2);i++)
	{
		if(num%i==0)
		{
			prime=0;
			break;
		}
	}
	return prime;
}

Output

Enter maximum range (n): 100
Prime numbers:  
2 3 4 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97  





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.