getting free/prim numbers to 1000

Why are this two loops different? How are this {} brackets affecting the result?

bool freeNumb;

for (int i = 0; i <= 1000; i++)
{
freeNumb = true;
for (int j = 2; j < i; j++)
{
if (i%j == 0)freeNumb = false;
if (freeNumb == true)cout << i << endl;

}


}


bool freeNumb;

for (int i = 0; i <= 1000; i++)
{
freeNumb = true;
for (int j = 2; j < i; j++)

if (i%j == 0)freeNumb = false;
if (freeNumb == true)cout << i << endl;




}





Last edited on
If no brackets, then only 1 statement following the loop get repeated in the loop.
If brackets, then the loop repeat all the statements inside the block delimited by brackets.

1
2
3
4
5
6
7
8
9
10
11
12
loop1()
{
   //do this line
   //then this line
   // then this line, then go back on top and start over
}

loop2()
//loop over this line many many times
//*this line has NOTHING to do with loop2*\\

Last edited on
This is why it's so important to use consistent indenting in your code. Humans tend to read the block structure of code from the indenting, even if compilers read it from the braces. Here is the indented code. The difference is obvious.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
bool freeNumb;

for (int i = 0; i <= 1000; i++) {
    freeNumb = true;
    for (int j = 2; j < i; j++) {
        if (i % j == 0)
            freeNumb = false;
        if (freeNumb == true)
            cout << i << endl;
    }
}

bool freeNumb;

for (int i = 0; i <= 1000; i++) {
    freeNumb = true;
    for (int j = 2; j < i; j++)
        if (i % j == 0)
            freeNumb = false;
    if (freeNumb == true)
        cout << i << endl;

}

Thx a lot the difference is really obvious :D it's amazing how little thing affect the end result.
Last edited on
Topic archived. No new replies allowed.