I don\'t know if I\'m just being a total fool, most likely I am, it\'s been a long day, but this isn\'t working as I want it to, and, well, I don\'t see why.
It sho
You have 10 elements in the array, numbered 0 - 9. You are overflowing the buffer, so all bets are off. This is undefined behaviour.
You can't add eleven entries to a ten-element array.
If an array is a[10], then every array starts from its index number 0, so here it will have 10 elements; given that their positions will start from 0 to 9, counting gives 10 elements.
You can try this:
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();
}
You have problems with your array declaration. You are defining an array of size 10 array[10]
and saying the program to calculate the sum of 11 elements which is resulting in memory overflows.
To correct the program just increase size of the array as array[11]
. Also if you wish you can check the recursive approach to find sum of array elements.
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;
}
int main()
{
//this the sum of integers in an array
int array[] = { 22,2,2,1,5,4,5,7,9,54,4,5,4 },x,sum=0;
int cout_elements = sizeof(array) / sizeof(int);
for (x = 0; x < cout_elements; x++) {
sum += array[x];
}
printf("%d",sum);
return 0;
}