First of all, this may seem duplicate with this question, but in my case, why did this only happen in the 1st loop iteration (input for the 1st array element). Why not all?
My code:
#include "stdio.h"
int main(int argc, char const *argv[])
{
int a[5];
int i;
for (i = 0; i < 5; i++) {
printf("Input a[%d]:\n", i);
int x = scanf("%d ", &a[i]); // notice the white-space after %d
}
for (i = 0; i < 5; ++i)
{
printf("a[%d]=%d\n", i, a[i]);
}
}
Output example:
Input a[0]:
1
2
Input a[1]:
3
Input a[2]:
4
Input a[3]:
5
Input a[4]:
6
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
Why did it ask for input twice only for a[0]
but not for the rest, and also why the value assigned to a[1-5]
is the value that was input in the one loop iteration before it?
I read this answer, but I still don't understand why it didn't ask for input twice in each loop. Any clear explanation?