• 0

Working / Non working C++ code


Question

I'm still very much an amateur with C++, so please don't get too technical with me.

I made a simple app which will list all the prime numbers starting with 1. For how simple it was, it turned to be a real pain to get it to work.

This is the working code:

#include <iostream>

using namespace std;

main()

{

int value = 1, mod = 2, loop = 0, temp = 0;

while(loop < 1){

temp = value % mod;

if(temp != 0) { mod++; }

else { value++; mod = 2; }

if(mod * mod > value) { cout << value << endl; value++; mod = 2; }

}

system("pause");

return 0;

}

Now if I simply replace 'else' with another if function:

while(loop < 1){

temp = value % mod;

if(temp != 0) { mod++; }

if(temp = 0) { value++; mod = 2; } //changed the else here to an if

if(mod * mod > value) { cout << value << endl; value++; mod = 2; }

all it does is list 1, 2, 3, and doesn't do anything from there.

I know I got it working, but I would like to know why using the if doesn't work correctly, for future reference.

Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Your code didn't work for me. It would skip 2.

This code appeared to work for me.

if( temp != 0 )
{
...
}
else if( temp == 0 &amp;&amp; value != 2 )
{
...
}

At least, I think that is what you're trying to accomplish. Also, when testing equality, use a ==. A single = is assignment.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.