Search code examples
sumansi-c

C Program that adds together square numbers - doesnt work


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.


Solution

  • 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,

    1. remove = on the first loop.
    2. reduce 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.