-1
#include <stdio.h>
int sumofelements(int a[],int size)
{
   int i,sum=0;
   for (i=1;i<=size;i++)  
   {
      sum+=a[i];
   }
   return sum;
}

int main()
{
   int a[]={1,2,3,4,5};
   int size=sizeof(a)/sizeof(a[0]);
   int soe=sumofelements(a,size);
   printf("sum of the elements=%d\n",soe);
}

The error in the sumofelements where the for loop if it starts with 1 it produces garbage value.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
janani
  • 1
  • 1
  • 2
    Because when you use `for (i = 1; i <= size; i++)`, you're reading out of bounds of the array, invoking undefined behaviour. The elements available are from`a[0]` to `a[size-1]`. Don't read out of bounds of an array. In C, idiomatic loops use `for (int i = 0; i < size; i++)`. – Jonathan Leffler Mar 13 '20 at 16:14
  • Why would you start by 1? You would omit one element with that, since index counting start by 0 for the first element. – RobertS supports Monica Cellio Mar 13 '20 at 16:29
  • There's nothing wrong with the `for` statement. The sum should be `+= a[i-1];` – stark Mar 13 '20 at 17:16

2 Answers2

5

This loop:

for (i=1;i<=size;i++)  
{
   sum+=a[i];
}

uses a[1], a[2], a[3], a[4] and a[5]

This loop:

for (i=0;i<size;i++)  
{
   sum+=a[i];
}

uses a[0], a[1], a[2], a[3] and a[4]

There is no a[5]. And you forgot a[0]. So the second loop gives you the right answer, and the first loop doesn't.

user253751
  • 57,427
  • 7
  • 48
  • 90
1

Because with the for loop condition i <= size, you would read beyond the bounds of the array a points to, at the last iteration of the loop, which is the reason that the program has undefined behavior.

If you would use i < size this would be correct, despite it makes less sense to set i to 1 because index counts start at 0 and you would omit one array element with that, which is kind of vital if you count all values of each elements together.

I think your whole confusion is made just because you probably think that the first element would be a[1], which it is not - it is a[0].

Thus, the one and only solution to define sumofelements() properly is:

int sumofelements(int a[],int size)
{
   int i,sum=0;
   for (i=0;i<size;i++)  
   {
       sum+=a[i];
   }

   return sum;
}