So I want to create an array with all the square numbers up to 1000000. And then I add the numbers together. Here is my code.
#include <stdio.h>
int main(void){
int squareNumbers[1000];
int i = 0;
int sum = 0;
while (i <= 1000){
squareNumbers[i] = i*i;
i++;
}
while (i >= 0) {
sum= sum + squareNumbers[i];
i--;
}
printf("Sum: %d", sum);
My problem is that I can execute the program however the printf in the end doesn't work.
First of all, your code references to an index that is out of the array's range.
On the first while
loop, i
increases up to 1001
and references squareNumbers[1000]
, which is over the maximum index it can have (999).
To fix this,
=
on the first loop.i
by 1 after the first loop.code:
int squareNumbers[1000];
int i = 0;
int sum = 0;
while (i < 1000){
squareNumbers[i] = i*i;
i++;
}
i--;
while (i >= 0) {
sum= sum + squareNumbers[i];
i--;
}
printf("Sum: %d", sum);
However, this will sum from 0*0
to 999*999
following the range of i
.
So you can change from
squareNumbers[i] = i*i;
to
squareNumbers[i] = (i+1)*(i+1);
So it has the sum from 1*1
to 1000*1000
.