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]);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With