#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
long int n,j=0,i,k,f=0;
cout<<"Enter the number of which you want to display the nth Prime number \n";
cin>>n;
for(i=2;;i++)
{
for(k=2;k<=i;k++)
{
if(i%k==0&&i!=2&&i!=k)
{
f=1;
}
}
if(f==0)
{
++j;
if(j==n)
{
cout<<"nth Prime number is"<<i;
getch();
exit(0);
}
else
cout<<"Trying";
}
}
}
This is the code I wrote to accept a number n, and display nth prime number using if else, for loop.
But it is not giving the desired output.
when inputting any value of n above 2 then output is
TryingTrying
and then nothing happens and I have to close the program manually.
Is their anything wrong with my code.
Any kind of help will be appreciated.
Thanks in Advanced.
Well actually I realized my mistake and now program is working.
This is what program should have been.
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
long int n,j=0,i,k,f=0;
cout<<"Enter the number of which you want to display the nth Prime number \n";
cin>>n;
for(i=2;;i++)
{
f=0;
for(k=2;k<i;k++)
{
if(i%k==0&&i!=2)
f=1;
}
if(f==0)
{
++j;
if(j==n)
{
cout<<"nth Prime number is"<<i;
getch();
exit(0);
}
}
}