The variable
squares
is defined at the global level. As such you cannot assign values to it in the global space as a series of assignment statements. You may, however assign a value at the same time as you define a global variable e.g.
int squares[20] = { 0, 1, 4, 9, 16, 25, 36, 49, 64
81, 100, 121, 144, 169, 197,
225, 246, 289, 324, 361 };
Probably a better idea, though is to assign the values in a loop inside main
int squares[20];
int main()
{
for(int i = 0; i < 20; ++i)
squares[i] = i * i;
}
Note that this also avoids data errors, like the one you have in your data. Every programmer learns that its usually better to have the computer do "donkey work" of filling in data like this than risking a brain "oops" or character transposition or other typo in hand typed data. We all know that the square of 16 is 256, but your computer doesn't know that your array
squares
should contain the square of the index at each element, so if you mistakenly typed 265, it's happy with that. Tracking that kind of error down can be very difficult - as the brain will often show you what you're expecting, so you can convince yourself that 265 is indeed the square of 16, so the program is generating bad results for an unknown reason.
I would also suggest that A) using global variables is, generally, a bad idea, and B) there's no reason to have the
squares
array in this case - all the data can be computed at run time. Unless you needed the values a
lot (think millions, or even billions), its doubtful there's any real-time measurable time difference between computing the square of a number and getting a value from an array.