blackroad
blackroad

Reputation: 39

Array and while scanf crash

#define LEN 200
int main()
{
    int arr[LEN],i;
    for (i =0; i < LEN; i++)
        while(scanf("%d", arr[LEN]) == 1){
            if((arr[LEN] == arr[LEN]+1) || arr[LEN] < 0){
            printf("Bad numbers.\n");
            }
            else if(arr[LEN] == 0){
                break;
            }
        }
    printf("Break");
return 0;
}

My point is if I'm writing numbers that are different and greater than 0 and arr[5] is different from a[12] or a[any other] it should save it into the array. But else if arr[LEN] == 0 it should stop scanf and save read numbers into the array and then continue with other stuff. After a few numbers, my code crashed. Can somebody help me?

Upvotes: 0

Views: 609

Answers (1)

sopho-saksham
sopho-saksham

Reputation: 181

  1. Inside the for loop, you need to use arr[i] instead of arr[LEN]. Truly speaking, arr[LEN] declaration creates an array of name arr with index ranging from 0 to LEN-1. So arr[LEN] is out of range of your array.
  2. In scanf, you need to use &arr[i] instead of arr[LEN].
  3. In the if condition you need to write if(arr[i] == arr[i-1]) because you can compare presently input value only with previous value, not with next value which has not been entered yet. But make sure you handle this condition separately for i=0 because then i-1 will not be an element of array.

I think these changes will make your code work smoothly for all values. Also, if you want to make sure that all array values are different then you have to compare present input value with all the previously stored values. Because current value might be different from just previous value but may be similar to value entered even before that.

Upvotes: 1

Related Questions