+ 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]?
5 Answers
+ 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)
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!
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?
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
0
thank u very much..i understand it now.