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 trialStefan Mach
3,691 PointsWhy does this work perfect in xCode but not here?
I copy pasted this code as written into xCode and set some break points. It looped up until and including 25 and then set isComplete to TRUE. Why does it work in xCode but not here?
Thanks,
Stefan
int mathTotal;
bool isComplete;
for (int i=5; i <=25; i++) {
mathTotal = i;
}
isComplete = TRUE;
3 Answers
andren
28,558 PointsBecause your code working and actually doing what the challenge asks for are not the same thing. The challenge asks you to add (not set) the incrementing value to the mathTotal
variable inside the loop, you are not adding the value to it. Instead you are setting the variable equal to the value.
In other words after the first loop mathTotal
should equal 5, after the second loop it should equal 11 (5+6) then 29 (11+7) and so on. With your loop it equals 5 in the first loop, 6 in the second and 7 in the third. As you can see your code is not achieving the desired effect.
You can fix your code by simply changing the =
operator to +=
like this:
int mathTotal;
bool isComplete;
for (int i=5; i <=25; i++) {
mathTotal += i;
}
isComplete = TRUE;
+=
adds the value on the right to the variable on the left, instead of simply replacing it entirely like the =
operator does.
Stefan Mach
3,691 PointsThanks for the correct answer. Don't recall being introduced to the += .
andren
28,558 Points+=
is just a shortcut, you could have used mathTotal = mathTotal + i
instead and had the same effect. I just find the +=
operator to be more convenient.
Stefan Mach
3,691 PointsAgain Thanks.