In this program, we are going to print prime numbers in c++ using the following methods:

- Prime numbers upto n
- Prime numbers between 1 to 100
- Prime numbers in a given range

Basic knowledge required: for-loop & if-else.

## C++ program to print prime numbers upto n

We have to print prime numbers from 1 to n where n is upper range. The upper range is given by the user according to his/her choice.

#include<iostream>

using namespace std;

int main()

{

int n,i,j;

cout<<"Enter upper range:";

cin>>n;

cout<<"\n Prime Numbers from 1 to "<<n<<": ";

for(i=1;i<=n;i++)

{

for(j=2;j<=i;j++)

{

if(i%j==0)

break;

}

if(i==j)

cout<<j<<" ";

}

return 0;

}

Output:

Enter upper range:50

Prime Numbers from 1 to 50: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

## C++ program to print prime numbers between 1 to 100

In this program, we have to print prime numbers from 1 to 100.

#include<iostream>

using namespace std;

int main()

{

int i,j;

cout<<"\n Prime Numbers from 1 to 100: ";

for(i=1;i<=100;i++)

{

for(j=2;j<=i;j++)

{

if(i%j==0)

break;

}

if(i==j)

cout<<j<<" ";

}

return 0;

}

Prime Numbers from 1 to 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

## C++ program to print prime numbers in a given range

In this program, we have to display prime numbers in a given range i.e., lower limit to upper limit. The lower limit, as well as the upper limit, is given by the user according to his/her choice.

#include<iostream>

using namespace std;

int main()

{

int l,u,i,j;

cout<<"Enter lower limit:";

cin>>l;

cout<<"Enter upper limit:";

cin>>u;

cout<<"\n Prime Numbers from "<<l<<" to "<<u<<": ";

for(i=l;i<=u;i++)

{

for(j=2;j<=i;j++)

{

if(i%j==0)

break;

}

if(i==j)

cout<<j<<" ";

}

return 0;

}

Enter lower limit:10

Enter upper limit:50

Prime Numbers from 10 to 50: 11 13 17 19 23 29 31 37 41 43 47

**About this post:**

This C++ program to print prime numbers upto n is made by Siddharth Jha. If you have any queries related to this post, deliver your query in the comment box we will reply to you as soon as possible.

**Related Post:**Prime number program in c

Menu-Driven Program using Switch Case and Do-While Loop

C Program for Multiplication of Matrix

## Post a Comment

## Post a Comment