Beginner's issues in Trivia

So I am quite new to C++. It does take time before things stick to my brain and it is not easy to grasp its logic.

I have an issue understanding how code works exactly and how it ends up being this and that result. I use an iOS app called Learn C++ and I do their trivias/quizes, while I may be answering correctly at times, I sometimes also do it without seeing how it ends up being that way (luck or a guess)...

Can someone please explain to me how the output of this becomes 26? I feel really dumb I do but, I don't piece it together, I'd say 21 LOL. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
	int a[4] = { 7,9,3,4 };
	for (int i = 1; i < 4;i++) // init,condition;increment ; i contains 1 from the first loop right?
	{ //statement
		a[0] += a[i] + 1; // so.. [0] (which is 7, first in array index?) = [0] + [i] + 1
	}
	cout << a[0]; // output result to screen (26 -- how is it 26?)
	system("pause"); // i know i shouldn't use this but since i'm just learning
}
Last edited on
Line 11: You're executing this line within a for loop which executes the line for a[1-3]. Effectively:
1
2
3
a[0] += a[1] + 1;  // 7 + 9 + 1 = 17
a[0] += a[2] + 1;  // 17 + 3 + 1 = 21
a[0] += a[3] + 1;  // 21 + 4 + 1 = 26 



Last edited on
Thanks!!

This will be useful in fully understanding it, I see a lot clearer now what I missed.

My thinking was at the for loop that it would be +1 then +2 then +3... (Which I suppose it is, but it jumps through all the arrays numbers instead)

Yeah let's just say it was a brain mess.
Last edited on
Topic archived. No new replies allowed.