1

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

3
  • 2
    Please no pictures of input and output, just include them in your question, easier to reproduce... Commented Jun 27, 2021 at 15:04
  • 1
    Your program has undefined behavior since you don't return an int from printArrayElementsSum and you also have signed integer overflow which means that your int can't handle numbers that big. - I also agree with @alex01011. It's very hard to copy/paste the figures you've used in your question when you have them as pictures. Commented Jun 27, 2021 at 15:04
  • 1
    Does this answer your question? What is signed integer overflow? Commented Jun 27, 2021 at 15:11

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

1 Comment

You also might want to change the function type to void print..() since you are not actually returning anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.