on Leave a Comment

C++ Program to Print Prime Numbers in a Given Range

This article contains C++ Program to Print Prime Numbers in a Given Range.

To understand this you need to understand these concepts :




Assume that user has entered a range of 10 to 20. Then prime numbers between 10 and 20 is 11, 13, 17, 19. You need to print these prime numbers using c++ programming code. 

C++ Program to Display Prime Numbers in a Given Range

#include<iostream>
using namespace std;
int main()
{
    int first,second,i,flag;
    cout<<"Enter first number : ";
    cin>>first;
    cout<<endl<<"Enter second number : ";
    cin>>second;
    if(first>second)
    {
        int t;
        t=first;
        first=second;
        second=t;
    }
    cout<<endl<<"Prime numbers between "<<first<<" and "<<second<<" : ";
    for(;first<=second;first++)
    {
        flag=0;
        for(i=2;i<first/2;i++)
        {
            if(first%i==0)
            {
                flag=1;
                break;
            }
        }
        if(flag==0)
        {
            cout<<first<<"\t";
        }
    }
    return 0;
}

OUTPUT 1:

Enter first number : 20

Enter second number : 30

Prime numbers between 20 and 30 : 23    29


OUTPUT 2:

Enter first number : 35

Enter second number : 45

Prime numbers between 35 and 45 : 37    41      43


OUTPUT 3:

Enter first number : 100

Enter second number : 85

Prime numbers between 85 and 100 : 89   97

0 comments:

Post a Comment