Help me understand how the program works.
I take it from the book of Steven Pratt “Program language C” I find on page № 289 exercise №6.
It's a program, her code here:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
while (i<3) {
switch (i++) {
case 0 : printf ("fat ");
case 1 : printf ("hat ");
case 2 : printf ("cat ");
default : printf ("Oh no ");
}
putchar('\n');
}
return 0;
}
Please correct me if I am not right at all. Right now, I would like to explain how it works. Firstly to work the function “while” three times.
The variable “i” has first time value 0. Then during the function "while" work, the variable has to be added three times three times.
As a result of program work, I had this result:
fat hat cat oh no
hat cat oh no
cat oh no
But I can't understand how I've got such a result. I am used to IDE CodeBlock, and my compiler works well. I changed the program code many times to understand how it worked at all. I changed the operatore "case".
Right now I changed the program kode so:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
while (i<2) {
switch (i++) {
case 1 : printf ("fat ");
case 2 : printf ("hat ");
case 3 : printf ("cat ");
default : printf ("Oh no ");
}
putchar('\n');
}
return 0;
}
After I got such a result:
oh no
fat hat cat oh no
But I can’t understand why the program works so? In my opinion the program must give such a result at all:
fat
Oh no
I think result or program work, must be only so. Why the program work so?