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 trial

iOS Objective-C Basics (Retired) Functional Programming in C Control Flow - For Loops

Stephen Hancock
Stephen Hancock
4,888 Points

Value of i

I am not sure I understand why 'i' isn't auto incremented the first time before the sum += many [i]. So the out put would just read 'sum is 4' then 'sum is 12' Can someone help me understand why it doesn't auto increment the first time. thanks

Stephen Hancock
Stephen Hancock
4,888 Points

--- objective c

int main() {

int many[] = { 2, 4, 8};
int sum = 0;
for (int i=0; i < 3; i++) {
sum += many[i];
printf("sum is %d\n", sum);
}

return 0;

}

1 Answer

The third parameter is a step and is executed only after the first cycle of the loop. So the first time the code is executing the first two are statements that are run i.e., initialize and then check if the condition is true. The second iteration onwards, check is done and then the step and the rest of code within the braces.

If you would like to take the step first and then the other stuff you can use the while loop.

Stephen Hancock
Stephen Hancock
4,888 Points

Thank you Kolapalli, that seems to make sense.