Sai Sampath
Sai Sampath

Reputation: 3

how to use long long int and remove segmentation fault

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

int main() {
    long long int a[10^9],sum=0;
    int n,i,length;
    scanf("%d",&n);

    for(i=0;i<n;i++)
    {
        if(0<=a[i]<=10^10)
        {
        scanf("%lld",&a[i]);
        }
   }

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

    printf("%lld",sum);
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}

i dont know the reason why i am getting the segentation fault this code runs fine for this input 1000000001 1000000002 1000000003 1000000004 1000000005

Upvotes: 0

Views: 1694

Answers (1)

Eric
Eric

Reputation: 24944

Issues in your code:

  • 0<=a[i]<=10^10 is not correct, should change to 0<=a[i] && a[i]<=(10^10)
  • ^ is a bitwise xor, not power,
  • In your for loop, you always compare before read element of a[], so you need to read first, then compare.
  • use unsigned long long, don't need int at end.

Check this code:

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

#define MAX_NUM 1000000000ULL
#define MIN_NUM 0ULL

int main() {
    int n,i;
    printf("input number count: ");
    scanf("%d",&n);
    unsigned long long a[n],sum=0;

    for(i=0;i<n;i++) {
        printf("input number[%d]: ", i);
        scanf("%llu",&a[i]);
        if(a[i]<MIN_NUM || a[i]>MAX_NUM) {
            a[i] = 0;
            printf("\t(ignored, due to out of range [%llu, %llu])\n", MIN_NUM, MAX_NUM);
        }
    }

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

    printf("\nsum: %llu\n",sum);
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}

Upvotes: 4

Related Questions