Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop is running more than specified in C? Why? [closed]

Tags:

c

loops

scanf

If I enter the number 5, this loop has to run 5 times but it is running 6 times. What is the problem?

 int main(){
        int i, *arr, size;
        printf("Please enter the Number: ");
        scanf("%d ",&size);
        arr = (int*) malloc(size * sizeof(int));
        for(i = 0; i < size; i++){
            scanf("%d ", &arr[i]);
        }
 }
like image 369
Murali krishna Avatar asked Mar 03 '16 08:03

Murali krishna


1 Answers

Remove the trailing space from the scanf() format string being used in the loop.

It causes scanf() to discard all whitespace after having read an int (%d), until it finds something that is not whitespace. On the fifth iteration of the loop, scanf() reads the int, and keeps going until it finds non-whitespace. This gives the illusion of needing to read one more integer.

On the last call of scanf(), any non-whitespace character after the integer data will cause reading to end.

like image 144
Peter Avatar answered Oct 22 '22 11:10

Peter