Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find sum of elements in the array

Tags:

arrays

c

I have this program which worked find in my college lab, but when I run it at my home it gives different result

#include <stdio.h>
int main(int argc, char* argv[]) {
        const int size=100;
        int n, sum=0;
        int* A = (int*)malloc( sizeof(int)*size );
        for (n=size-1; n>0; n--)
                A[n] = n;

        for (n=0;n<size; n++)
                sum += A[n];

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

}

I'm expecting 4950 as result but I keep getting different result like 112133223. Why is this happening ?

like image 512
Makesh Avatar asked Mar 26 '26 23:03

Makesh


1 Answers

You are not assigning value to A[0]. As a result of this A[0] will have garbage value which is getting added to sum.

Change

for (n=size-1; n>0; n--)
               ^^^

to

for (n=size-1; n>=0; n--)
               ^^^^

Also you need to free the dynamically allocated memory by doing:

free(A);

before you return.

like image 76
codaddict Avatar answered Mar 29 '26 13:03

codaddict



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!