\n
in scanf
was the problem
#include<stdio.h>
int main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
printf("\nEntered values:\n");
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
return 0;
}
Reason:
I expect only 3
values is stored in an array but it stores 4 values
and in next 'for' loop as expected show 3 values. My Question is why
in 1st 'for' loop it takes 4 values instead of 3?
First: No, it only stores 3
number but not 4
numbers in array marks[]
.
Second: interesting to understand loop runs only for three times for i = 0
to i < 3
. The for loop runs according to condition. More interesting code is stuck in scanf()
as described below:
Your confusion is why you have to enter four numbers, its not because you loop runs 4
times but its because scanf()
function returns only when you enter a non-space char (and after some enter press you inputs a number symbol that is non-space char).
To understand this behavior read manual: int scanf(const char *format, ...);:
A sequence of white-space characters (space, tab, newline, etc.; see
isspace(3)
). This directive matches any amount of white space,
including none, in the input.
Because in first for loop's, in scanf()
you have included \n
in format string, so scanf()
returns only if press a number enter (or a non-space key).
scanf("%d\n",(marks+i));
^
|
new line char
What happens?
Suppose input to program is:
23 <--- because of %d 23 stored in marks[0] as i = 0
<enter> <--- scanf consumes \n, still in first loop
543 <--- scanf returns, and leave 542 unread,
then in next iteration 543 read by scanf in next iteration
<enter>
193
<enter> <--- scanf consumes \n, still in 3rd loop
<enter> <--- scanf consumes \n, still in 3rd loop
123 <--- remain unread in input stream