Could someone please help me understand what is happening here:
// arrays example
#include <iostream>
using namespace 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;
}
I am following a tutorial on C++ and doing quite well at it but I always get stuck on arrays.
The output of this is 12206 but I can't work out why, the tutorial usually explains everything or I can usually work it out for myself but here I can't get my head around it.
I understand that 12206 is the sum of the array contents but I don't know how that happens.
It looks as if the for loop declares the size of the array as zero (n=0) and then increments the elements by one (n++) and then when it reaches the condition of no more than 5 elements (n<5) passes the value of Billy [n] (where n would be 5) to using the += (right to left operator) to result which is then displayed.
If I'm right (and please correct me if im not) then why does the example code make an issue of declaring the number of elements within the array of as 0? I thought by default C++ would automatically assign the number of elements based on the initialization values.
// arrays example
#include <iostream>
using namespace 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;
}
I am following a tutorial on C++ and doing quite well at it but I always get stuck on arrays.
The output of this is 12206 but I can't work out why, the tutorial usually explains everything or I can usually work it out for myself but here I can't get my head around it.
I understand that 12206 is the sum of the array contents but I don't know how that happens.
It looks as if the for loop declares the size of the array as zero (n=0) and then increments the elements by one (n++) and then when it reaches the condition of no more than 5 elements (n<5) passes the value of Billy [n] (where n would be 5) to using the += (right to left operator) to result which is then displayed.
If I'm right (and please correct me if im not) then why does the example code make an issue of declaring the number of elements within the array of as 0? I thought by default C++ would automatically assign the number of elements based on the initialization values.
) out, you can use a pointer to point to a dynamically allocated area of memory to create arrays at runtime. With a static variable assigned at runtime, it points to a statically allocated area of memory which cannot be changed size-wise.