arraysc

added add two arrays but the code is acting like a random number generator . using an online c compiler


this was the c code I was working with ;

#include <stdio.h>

int main() {
    int numbers[3];
    int median[3];
    int sum[3];
     
    sum[3] = numbers[3] + median[3];
    numbers[0] = 1;
    numbers[1] = 3;
    numbers[2] = 7;
    numbers[3] = 5;
    
    median[0] = 1;
    median[1] = 12;
    median[2] = 10;
    median[3] = 44;
    
    printf("sum=%d",sum);
    
    return 0;
}

I wanted to add the arrays but the output is some random 9 digit +ve number or 10 digit -ve number. I would love to know what is actually happening in the background.


Solution

  • The line

    sum[3] = numbers[3] + median[3];
    

    doesn't do what you want; it doesn't establish a formula to add all the elements of numbers to all the elements of median and assign the result to the elements of sum; it only adds a single element of each array (which is out of range - your array indices only go from 0 to 2) and assigns the result to a single element of sum.

    You will have to perform the operation on each element individually:

    for ( int i = 0; i < 3; i++ )
    {
      sum[i] = numbers[i] + median[i];
      printf( "sum[%d] = %d\n", i, sum[i] );
    }
    

    Again, your array indices only go from 0 to 2, so the lines

    numbers[3] = 5;
    

    and

    median[3] = 44;
    

    are erroneous. You either need to remove them or declare all your arrays with 4 elements:

        int numbers[4];
        int median[4];
        int sum[4];