Inside of:
for (i = 1; i < 10; i++) {
scanf("%d\n", &num[i]);
}
max = num[0];
max
has an indeterminate value because the loop's counter variable i
starts at 0
, not 1
which gives the result that the first element of the array wasn't assigned inside of the loop. So you end up assigning this indeterminate value to max
.
To use an indeterminate value in the following code:
if (max < num[i]) {
max = num[i];
}
invokes undefined behavior.
"However, if I change i=0
, the program asks me for 11 inputs before moving on. And among those 11 inputs, the program still won't count the last one, if it is the largest."
"When running it, if the largest element is the last one, the code won't recognize it. Why is that?"
It doesn't actually ask you for an 11th input for any presumed 11th array element as you think it does and the last in the loops1 treated element of the array is not the one you think it is. That is just an impression to you.
This behavior is caused by the newline character in the format string of the scanf()
call:
scanf("%d\n", &num[i]);
The newline character (\n
) is equal to any white space and with this directive, scanf()
reads an unlimited amount of white space characters until it finds any-non white space character in the input to stop consuming and the control flow continues to the next statement.
Why does scanf ask twice for input when there's a newline at the end of the format string?
It doesn't ask for the input of the 11th element of the array (as you think it does). It simply needs any non-white space character that the directive fails.
The last element of the array (which is treated inside of the loops1) is still the 10th (num[9]
), not the 11th (num[10]
) and so is the output correct when you initialize the counter to 0
and it prints:
The biggest nr is: 10
because 10
is the value of the last treated element num[9]
.
1) Note that you made a typo at the declaration of num
-> int num[100];
. With this you define an array of one hundred elements, but you actually only need one of 10
elements -> int num[10];
.
Side Note:
Also always check the return value of scanf()
!
if (scanf("%d\n", &num[i]) != 1)
{
// Error routine.
}