Calculating the sum of integers in an array

I don’t know if I’m just a complete fool, most likely I, it was a long day, but it doesn’t work as I want, and, well, I don’t see why.

It should be able to enter 11 numbers, a new number on each line, add them to the array, and then sum them, but it just doesn't work. It does not stop to exit the loop, although I increase i.

Any ideas?

int main(void) {
 int array[10];
 int i;
 int sum = 0;
  for ( i = 0; i < 11; i++){
   scanf("%d", &array[i]);
  }
  for (i = 0; i < 11; i++) {
   sum += array[i];
  }
printf("%d", sum);

return 0;

}

+5
source share
8 answers

You have 10 elements in the array, numbered 0 - 9. You overflow the buffer, so all bets are disabled. This behavior is undefined.

+4
source

You cannot add eleven entries to a ten element array.

+3
source

- , for-loop 11 , 11- , , i.

11 10 for.

+3

10. , , undefined.

, undefined , , i array array[10] ( , ), i. , 11, .

+2

[10], 0, 10 ; , 0 9, 10 .

:

main()         
{        
    int a[10], i, n, sum=0;    

    printf("enter no. of elements");
    scanf("%d",&n); 
    printf("enter the elements");   

    for(i=0;i<n;i++)    
        scanf("%d",&a[i]);

    for (i=0;i<n;i++)
        sum=sum+a[i];

    for(i=0;i<n;i++)
        printf("\n a[%d] = %d", i, a[i]);

    printf("\n sum = %d",sum);
    getch();

}
+1
source

You have problems declaring an array. You define an array of size 10 array[10]and tell the program to calculate the sum of the elements 11 , which leads to memory overflows.

To fix the program, simply increase the size of the array as array[11]. Also, if you want, you can check the recursive approach to find the sum of the elements of an array .

0
source

Try the following:

void main() {
 int array[10];
 int i;
 int sum = 0;

  for ( i = 0; i < 11; i++){
   scanf("%d", &array[i]);
  }
  for (i = 0; i < 11; i++) {
   sum = sum + array[i] ;
  }
printf("%d", sum);

return 0;
}
0
source
int main()
{
    int a[10];
    int i,j;
    int x=0;
    printf("Enter no of arrays:");
    scanf("%d",&j);
    printf("Enter nos:");
    for(i=0;i<j;i++)
    {
        scanf("%d",&a[i]);
    }
    for (i=0;i<j;i++)
    {
        x=x+a[i];
    }
    printf("Sum of Array=%d",x);
    return 0;
}
-1
source

All Articles