sivaram
sivaram

Reputation: 79

I need to print the sum of a array using function in c

the following is my code im not getting the correct output can anyone say what is wrong with my code?

#include<stdio.h> 
#include<stdlib.h> 

int printArrayElementsSum(int *a,int n){
    int sum=0;
    for(int i=0;i<n;i++){
        sum+=a[i];
    }
    printf("%d",sum);
}

int main(){
    int N;
    scanf("%d",&N);
    int arr[N],index;
    for(index=0;index<N;index++){
        scanf("%d",&arr[index]);
    }
    printArrayElementsSum(arr,N);
    return 0;
}

enter image description here

Upvotes: 1

Views: 166

Answers (1)

Mark Lavin
Mark Lavin

Reputation: 1242

The problem is that you are trying to store the number 3000000023 in a 32 bit signed integer, which "wraps around" to yield your program's output. You canfix this by using long instead of int for your variables (and you'll have to change the %d format string to %ld).

Upvotes: 1

Related Questions