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

Why are the answers 2, 6, 14 instead of 2, 6, 11?

#include <stdio.h>
int main() {
     int many[] = {2, 4, 8};
     int sum = 0;
       for (int i = 0; i < 3; i++;) {
              sum += many[i];
              printf("sum %d\n", sum);
            }
     return 0;
}

2 Answers

<p>Think of what happens in the segment sum += many[i]; Another way to write that is: sum = sum + many[i];</p> <p> 2 = 0 + 2................when i=0, many[i] is 2 so the sum is 2!</p> <p> 6 = 2 + 4................when i = 1, many[i] is 4 so add that to the current value of sum.</p> <p> 14 = 6 + 8................when i=3, many[i] is 8 so add that to current value of sum.</p> <p> Hence the printed values of sum are 2, 6, 14! </p>

Very clear and concise, thank you!

Michael Hulet
Michael Hulet
47,913 Points

What you're doing here is creating an array of numbers (2, 4, 8), creating a variable to hold the sum as it is determined, then looping over each number in the array and adding it to the sum at that time. Each time the loop is run, the sum will be equal to all the numbers in the array before the one it's currently on, added together. Essentially, in its current state, it's equivalent to doing this:

int sum = 2 + 4 + 8;

Of course, the sum of 2 & 4 is 6, and the sum of 6 & 8 is 14. Thus, the final value of the sum is 14