Search code examples
arraysccastingaddition

Why does one method of adding all the elements of an array fail when similar methods succeed


I have an array of doubles. To simplify the example, I use an array of length 3. I want to add all 3 elements of the array. I do it in 3 ways. Here's the program to demonstrate.

#include <stdio.h>

int main()
{
  double   a[3] =  {1.,3.,5.};

  double sum1 = a[0]+a[1]+a[2];

  int i=0;
  double sum2 = (double)a[i]+(double)a[i+1]+(double)a[i+2];

  double sum3 = a[i]+a[i+i]+a[i+2];

  printf("sum1=%f sum2=%f sum3=%f \n",sum1, sum2, sum3);
}

When you run it, you get

sum1=9.000000 sum2=9.000000 sum3=7.000000

Why does sum3 fail, especially when it should be equivalent to sum1? And why do I have to cast the individual elements of the array to double when the array itself is an array of doubles?


Solution

  • In the Line :

    double sum3 = a[i]+a[i+i]+a[i+2];
    

    a[i+i] should be a[i+1].