Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMelvin Amador
5,239 PointsWhile Loop
Hi. I'm trying to complete a challenge on While Loops. My question is: why do I keep receiving an error on the following loop. I'm trying to say that as long as rubies are less than rubyMax then increment the rubies amount by the rubyReward.
int rubies = 0;
int rubyReward = 7;
int rubyMax = 50;
while (rubies < rubyMax)
{
rubies = rubyReward++;
}
bool levelFinished;
int rubies = 0;
int rubyReward = 7;
int rubyMax = 50;
while (rubies < rubyMax)
{
rubies = ++rubyReward;
}
2 Answers
Joe Scotto
8,282 Pointswhile (rubies < rubyMax)
{
rubies = rubyReward + 1
}
Danny Iachini
1,437 PointsrubyReward++
is a post-increment operator (meaning rubies would equal what rubyReward was before adding 1 to it)
++rubyReward
is a pre-increment operator (meaning rubies would equal what rubyReward was after adding 1 to it)
This StackOverflow answer has a really good explanation with examples.
When you asked to then increment the rubies amount by the rubyReward
, I believe what you're looking for is actually:
while (rubies < rubyMax)
{
rubies += rubyReward
}
Melvin Amador
5,239 PointsMelvin Amador
5,239 PointsThanks Joe
Danny Iachini
1,437 PointsDanny Iachini
1,437 PointsUnfortunately this snippet would cause an infinite loop with the variables provided in the question. The while condition would start at (0 < 50) (which is true) -- so then you'd set rubies to (7+1). The while condition the next time through would be (8 < 50) (still true) -- but rubyReward hasn't changed, so you would again set rubies to (7+1). The while condition the next time through would be (8 < 50) (and here's the pattern now -- rubies will never change to anything other than 8).
Instead (as answered below), I think inside your for loop, you want to be setting
rubies += rubyReward