2

I have a written a simple c code as follows

#include<stdio.h>
void main()
{
    int a[3];
    int i;
for(i=0;i<=2;i++)
{
    printf("i is %d\n",i);
    scanf("%d ",&a[i]);
}
for(i=0;i<=2;i++)
    printf("a[%d] is %d\n",i,a[i]);

}

The problem is when I run the program I have to enter two values when i is 0(not one) like this

i is 0
1
2
i is 1
3
i is 2
4

Even though the output is correct i.e.

a[0] is 1
a[1] is 2
a[2] is 3

why do I have to enter 4 values instead of 3 and why do the statement i is 1 not come before I enter 2?

  • to understand this behaviour read [this answer](http://stackoverflow.com/questions/17831060/store-data-in-array-from-input?lq=1) – Grijesh Chauhan Aug 09 '13 at 16:45

1 Answers1

1

Change:

scanf("%d ",&a[i]);

to:

scanf("%d",&a[i]);

That extra space is the source of all your problems, because it's eating whitespaces.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181