Q:

C++ program to display prime numbers

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Most popular and Searched C++ solved programs with Explanation and Output

Similar questions


need a help?


find thousands of online teachers now
C++ program to add two times... >>
<< C++ program to check prime number...