total noob at c plus plus
http://pastebin.com/hMMRUQVE
Would the answer for a) be 45 or 46?
Would the answer for b) be 25 or 26?
I don't get the + a[i] portion.
March 20, 2014
total noob at c plus plus
http://pastebin.com/hMMRUQVE
Would the answer for a) be 45 or 46?
Would the answer for b) be 25 or 26?
I don't get the + a[i] portion.
4 Comments • Newest first
a. 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
b. 1 + 3 + 5 + 7 + 9
For "total = total + a[i];" you get a different a[i] value [b]and[/b] a different total value each time you loop.
Since you loop 10 times, your "i" value will represent values from 0 to 9, where they correspondingly represent the storage placement for the integers in a[ ].
Barney style:
Loop 1 =
i = 0;
total =0;
total = total + a[i]; // total = 0 + a[0]. a[0] = 1, as 1 takes up the first slot in your array, [b]therefore[/b] total is now 1
i++ // this increases your i value by 1; same thing as saying "i = i + 1;"
Loop 2 =
i = 1;
total = 1;
total = total + a[i] ; // total = 1 + a[1], where a[1] = 2, [b]therefore[/b] total is now 3
i++;
Loop 3 =
i = 2;
total = 3; // therefore a[2] = 3, total = 3 + 3; new total = 6;
i++;
And so forth
It's one thing to be a noob, but this stuff isn't even pseudocode -- it's a direct implementation.
You could have easily copy-pasted it into an IDE and tossed in a print statement to find the answers.
45 and 25.
Helps to write the total during each loop.
a[i] just means "the value in the array that is at index i"
so if a[] = {1,2,3},
then a[0] = 1, a[1] =2, and a[2] = 3
at each time in the loop, you get a new value for i, use that i to evaluate a[i]