Reason for specific output. Since you don not have a break;
for switch conditions you fall through all the switch cases from the first match found
From this tutorial,
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
switch (i % 3) {
case 0: printf("zero, "); // <= No break so once this get match all the below will get execute. (Till a break is reached)
case 1: printf("one, ");
case 2: printf("two, ");
default: printf("what? ");
}
So in your case for i=0
to i=4
, following happens,
When i=1
you get i%3
will match with case 1
and output will be one,two,what?
.
When i=2
you get i%3
will match with case 2
and output will be two,what?
When i=3
you get i%3
will match with case 0
and output will be zero,one,two,what?
When i=4
you get i%3
will match with case 1
and output will be one,two,what?
And note that default
is the case given to fulfill when no case is met. but in your case since you do not have break
, this too get executed ans results for what?
.
And what puts()
does is , simply put a string to standard output. In your case puts(” “) will put a space. And note that puts()
will append a newline at the end.
2
solved C language, explain this code [closed]