Prime Number program not working!

The prime no. detecting program I wrote is not working....
The compiler seems to skip the loops... Please help me out... and tell me what is wrong.

Thanks in advance.. :D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 #include<iostream>
using namespace std;

int main(){
int a, b, c,d ;

cin>>a>>b;
c=2;
d=2;
while(c>a){
    if(a%c==0)
        cout<<a<<" is not prime\n";
    c++;
}
if(c>a)
    cout<<a<<" is prime\n";
while(d>b){
  if(b%d==0)
        cout<<a<<" is not prime\n";
    d++;

}
if(d>b)
    cout<<b<<" is prime\n";
return 0;
}
it works

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <conio.h>

using namespace std;


int main()
{
int num, sub, fac,lim;
cout<<"enter top limit: ";cin>>lim;
num=1;
while (num<=lim)
{
 fac=0;
 sub=1;
 while (sub<=num)
  {
if (num%sub==0)
fac++;
sub++;
  }
 if (fac==2)
 cout<<num<<"  ";
 num++;
 }
system("pause");
}
Thanks, for your code!
But I am quite confused of your code.. It works.. But can you explain me the logic>
Aside from the comment you received, I would like to give you the advice to use more detailed variables and use more space to write out the various operations. (For instance; I would personally name 'a' 'UI_number' (user input number).)

While this might indeed mean that you are taking up more space to write the same code, it has the advantage of clarity. From one beginning programmer to another; Readability far exceeds minimizing the length of the code.

I suggest that you re-write your own program with Ajuzoo's example next to it, step by step, so that you can better see what you are doing.
Line 10: while (c<a){
Remember, c starts at 2, and should increase until it equals a. Once c equals a, you stop the loop.

Line 15: if (c==a)
See above.


Notice that you are duplicating code. This is an indication that you should put stuff in a function, and call the function.

Hope this helps.
Topic archived. No new replies allowed.