Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,842 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