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 trialCarl David Graham
150 Pointsfor loop question
why isn't the int i = 0 placed outside of the for loop? Wouldn't the current code shown below cause the i variable to keep restarting to 0 each time the loop is run?
int main()
{
int many[] = { 2, 4, 8};
int sum = 0;
for (int i=0; i < 3; i++) {
sum += many [i];
printf("i %d sum %d\n", i, sum);
}
return 0;
}
2 Answers
Maximiliane Quel
Courses Plus Student 55,489 PointsHi Carl,
in the conditional statement you have three parts. The first part tells the loop where to start, i.e. you initialise to a starting value, the second part tells the loop when to stop and the third part tells it what to do after each loop is run. i++ means that your i will be incremented by one each time.
In other words you are saying: starting from 0 for as long as i is smaller than three execute the code block incrementing by one each time you ran through it.
If you wrote a while loop on the other hand, you would put a condition at the start and increment at the end of your loop statement.
Does that help?
Carl David Graham
150 PointsCool!
Carl David Graham
150 PointsCarl David Graham
150 PointsOoh...Cool. Yeah! That helps loads. :)
Matthew Mascioni
20,444 PointsMatthew Mascioni
20,444 PointsExcellent answer, Maximiliane Quel!
Maximiliane Quel
Courses Plus Student 55,489 PointsMaximiliane Quel
Courses Plus Student 55,489 PointsThanks. Glad I could help :0).