I've been reading up on the tutorial and I'm at the Arrays part of it. On the page there is the example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// arrays example
#include <iostream>
usingnamespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
The result is: 12206
Can anyone please explain this? Its not explained on the webpage really. I'm sure it's right infront of my face but just cant figure out how it got 12206.
Ok what a for loop does is it will loop for a specified amount of times. I'll go through the process step by step.
You know that an array calls multiple variables of that on data type. So you are opening an array of integer type named billy. This array has 5 spots but they are not labeled 1,2,3,4,5 they are labeled 0,1,2,3,4 so spot 0 = 16, spot 1 = 2, etc.
Now how a for loop works is you have it execute a piece of code a specified amount of times. So in your statement you set int n = 0, this will be your counter to where the loop will end. And you tell the loop to run as long as n is less than 5 (n < 5), and as for the n++, that means that every time the loop runs, n will add 1 each time. You are also using the counter for the loop to keep adding billy[whatever the number for n is] to result.
so if you want to look at in in full view
billy[0] = 16
add that to result = 16
billy[1] = 2
add that to result = 18
billy[2] = 77
add that to result = 95
billy[3] = 40
add that to result = 135
billy[4] = 12071
add that to result = 12206
so each time the loop runs it adds 1 to n, so you start will 0 than next loop n = 1 than next loop n = 2, etc.
So 'n' will increase by 1 until it is no longer 'less than' 5 right? When that happens, the loop will stop right? If so, this I understand. But what I dont understand is how the values in the array increase? Each time the loop does it's loop, does it add 1,2,3,4,5 somewhere to billy(the array)?
result += billy[n]; < -- There, I was thinking that the 'n' by Billy meant that 1 was increased to the array for each spot, which would equal the result.
+= means to increment by
a += c; means to add c to a and assign that value to a
so result += billy[n]; means to add billy[n] (whatever it is at the time) to result.
Since n goes up by 1 each time through the loop, billy[n] takes on each value of the array. So the first time through the loop, result is 0, but the value of billy[0] is added to it, which is 16. The next time through the loop the value of billy[1] is added to it, so it goes from 16 to 16+18. The third time through the loop the the value of billy[2] is added to result and so on. It helps to know that the array is indexed from 0 through 4 rather than from 1 to 5.
I'm not sure why you think the values in the array increase; they stay the same throughout the execution. result += billy[n] will not change anything in billy's values.