Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading