+ 1

Can some one help me to understand this?

int main() { int a[3] = {5,1,8}; for(int i=0; i<3; i++){ a[0]= a[0]+a[i]; } cout << a[0]; return 0; } outputs 19. does this mean a[0] + a[5+1+8]?

24th Nov 2016, 3:52 PM
Haikal Jama Shaywal
5 Respostas
+ 5
well the code in total evaluates to a[0]+a[0]+a[1]+a[2]=19 how? for i=0 a[0]=a[0]+a[0]. so a[0]=10(5+5) for i=1. a[0]=a[0]+a[1]. so a[0]=11(10+1) for i=2. a[0]=a[0]+a[2]. so a[0]=19(11+8)
24th Nov 2016, 4:28 PM
Megatron
Megatron - avatar
0
Essentially, yes, if im understanding the question correctly. a[0] = a[0] + a[I] in the for loop assigns a[0] to 5+5+1+8, since the addition statement loops until all the numbers in the list are added together. I hope that makes sense!
24th Nov 2016, 4:04 PM
Hazel "Joey" Pickett
Hazel "Joey" Pickett - avatar
0
thank you very much. what about if i change a[0] to [1]; int main() { int a[3] = {5,1,8}; for(int i=0; i<3; i++){ a[1]= a[1]+a[i]; } cout << a[1]; return 0; } outputs 20. how come 20; a[1] which is 1 + a[i] which is [5+1+8] the output suppose to be 15?
24th Nov 2016, 4:12 PM
Haikal Jama Shaywal
0
To answer your second question, it's in the argument order. Your basically going like this: First go of the loop a[0] = 5 and a[1] = 1, so their sum is 6. You have now assigned a[1] to 6. Second go of the loop a[1] = 6 and a[1] = 6, so their sum is 12. You have now assigned a[1] to 12. Third go of the loop a[1] = 12 and a[2] = 8, so their sum is 20. You have now assigned a[1] to 20. Sorry it took me so long to answer, I had a hard time trying to explain this in a paragraph without confusing you further. I think my last answer may have been problem Lol
24th Nov 2016, 5:13 PM
Hazel "Joey" Pickett
Hazel "Joey" Pickett - avatar
0
thank u very much..i understand it now.
30th Nov 2016, 6:47 AM
Haikal Jama Shaywal