3

The program below prints a value of size 20 no matter how small input we provide. Why?

#include <stdio.h>
#define LENGTH 20

int main(){
    int arr[LENGTH], size = 0;

    printf("Enter array elements (enter q to stop):\n");

    for (int i = 0; i < LENGTH; i++)
    {
        scanf("%d", &arr[i]);
        size++;

        if (arr[i] == 'q')
        {
            break;
        }
    }

    printf("size of array is %d", size);
    return 0;
}
3

The problem is with your scanf and the fact that you are telling it it will read an int but you give it a char. ASCII values may be represented by integers, but scanf can distinguish them. It checks for each digit to see if it's in the range 48-57 which is '0'-'9' in ASCII. So when it reads a digit that is not in that range ('q' for example), it puts it back into the input stream and it returns -1. Then it reads again from the input stream the same thing and again puts it back and returns -1 and so on. That's why your for loop runs until i becomes 20 and size has gotten 20 too. If you want to make sure that the input won't be inserted back into the input stream, you could use fflush(stdin) after each scanf but the 'q' won't be assigned anyway and your loop won't break. If you want alternatives, either use the GetInt() given by the staff or see that post: https://stackoverflow.com/questions/3302255/c-scanf-vs-gets-vs-fgets

3
  • good explanation, the loop doesn't stop until 20th iteration because you are comparing an integer value to a character which doesn't break your loop. and the size continues to increment until 20th iteration. Jul 11 '15 at 17:57
  • Actually the character IS represented as an integer, the problem is with the scanf. For example look at this code and result: gist.github.com/christosg88/7bd98e8adc29e68846db
    – ChrisG
    Jul 11 '15 at 18:22
  • Couldn't actually understand the whole stuff you told. But yes I got that the problem is with scanf herein. Jul 11 '15 at 19:46
0

This is a good question. It is being caused by the input of 'q' into an int (the array), but I can't explain why it is behaving as it is.

I tried running it, adding a printf to trace it and found that after entering 'q', it stopped asking for data, but continued to print and increment size within the loop for the full 20 passes.

I changed the code to detect when a 0 is entered and it worked as expected, so it's clearly the entry of 'q' that is triggering the behavior. But, why are some lines of code within the loop being executed and others are not?

That's WHAT is causing the problem. What I don't understand is why the program continues to cycle through the for loop, and why it is incrementing size++, but not executing the scanf command? Perhaps @kareem or someone far more versed in c can explain this.

1
  • I have answered it bellow @Cliff B
    – ChrisG
    Jul 10 '15 at 23:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .