Reputation: 129
I just started learning C++ by myself recently. I came across this problem:
print out all the integers between 1 and 100 that can't be divisible by 3,or 5,or 7.
I used both for
and while
loops in two different tests, the for
loop works okay, but the underscore keeps flashing after two loops for the while
loop. I included pictures when I accidentally asked this on the wrong SE site.
Why does this happen?
for loop
#include <iostream>
using namespace std;
int main()
{
int i=1;
for(i=0;i<=100;i++)
{
if(i%3==0||i%5==0||i%7==0)
{
continue;
}
cout<<i<<" ";
}
return 0;
}
while loop
#include <iostream>
using namespace std;
int main()
{
int i=1;
while(i<=100)
{
if(i%3==0||i%5==0||i%7==0)
{
continue;
}
cout<<i<<" ";
i++;
}
return 0;
}
Upvotes: 1
Views: 1998
Reputation: 2432
For a quick fix:
int main()
{
int i=1;
while(i<=100)
{
if(i%3==0||i%5==0||i%7==0)
{
i++;
continue;
}
cout<<i<<" ";
i++;
}
return 0;
}
Because when i
reaches 3, you're always satisfying the if
statement and never incrementing its value, so it's looping infinitely with a value of 3.
Edit: Quick fix aside, what I'd do is
int i=1;
while(i<=100)
{
//negate the if statement so continue is no longer needed
if(!(i%3==0||i%5==0||i%7==0))
cout<<i<<" ";
++i; //(pre)increment in one place
}
return 0;
Upvotes: 2
Reputation: 18944
The key difference between while
and for
is that for
loops do your incrementing (the third piece, in your case i++
) when you continue
and while
loops do not, because your incrementing is just another line of code somewhere in the loop. This is why one solution is to add the i++
before the continue. You can imagine that in some cases this might get tricky.
For this reason, some developers prefer for
if they're likely to continue. Others move to the next choice at the top of the while. Start at 0, increment it first, then check, now if you continue you'll be fine. And still others move the incrementing into the condition:
while(++i<=100)
I'm not recommending this exactly, I show it to you so that when you meet a while
loop that does the incrementing right in the condition you will understand one of the motivations for doing it that way.
There are lots of ways to do most things in C++, and the distinctions between them can be subtle. This will not be the last time you experience this.
Upvotes: 2