I get confused with these code segments(tracing). When a problem like this comes up I don't know how to solve it(on paper) I have a hard time understanding them. Can someone please help me with the steps and how the numbers change etc. to getting this output and some advice on how to understand them. Thank you
1 2 3 4 5 6 7 8 9
int s = 0, Size = 5 , list[5]={8,7, 3, 2,4};
for ( int j = 0; j < Size; j++ ){
s+= ++list[j];
cout << list[j] <<” “ ;
}
cout << s / size ;
Output:
List: 9 8 4 3 5 5
Lets reformat a bit (without changing the meaning) and fix one typo too.
1 2 3 4 5 6 7 8 9 10 11 12 13
int s = 0; // running sum
int Size = 5;
int list[Size] = {8, 7, 3, 2, 4}; // Size elements
for ( int j = 0; j < Size; ++j ) // Size iterations
{
++list[j]; // increment operation on dereferenced value
s += list[j]; assignment-version of add
cout << list[j];
cout << " " ;
}
cout << s / Size ; // the last printed value, note integer division that drops remainder
Hint: On first iteration j is 0, so array element list[j] is list[0] is 8. Then the element is modified and used.