C++ Programs
In the previous program (Prime and Composite Numbers) the user had entered any number and the output stated whether it was a prime or a composite number.
In this program, the user will enter any two different numbers and the output will be all the prime numbers between those two numbers.
For this, I am using user-defined-function in which I will be using for-loops and if-statements.
Code:
#include<iostream.h>
#include<conio.h>
void prime(int a,int b)
{
int i,j,k;
for(i=a;i<=b;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==0)
cout<<i<<"\n";
}
}
void main()
{
clrscr();
int a,b;
cout<<"\t"<<"\t"<<"Prime numbers between two numbers"<<"\n";
cout<<"From: ";
cin>>a;
cout<<"To: ";
cin>>b;
prime(a,b);
getch();
}
Output:
First Run:
Second Run:
Note: For finding composite numbers between any two numbers apply the same code but with just a slight change. In the prime function, in the outermost loop, the condition for the if statement has to be changed, i.e.,:
void prime(int a,int b)
{
int i,j,k;
for(i=a;i<=b;i++)
{
k=0;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
k=1;
}
if(k==1)
cout<<i<<"\n";
}
}
It gives all the composite numbers between any two numbers.
For any queries or suggestions please comment !
No comments:
Post a Comment