Reputation: 7
I cannot understand how this program works; can somebody explain?
I know that it is connected with state machine, but I do not understand how state machine works.
void abba();
int main()
{
printf("Enter 10 characters, a or b.\n");
abba();
return 0;
}
void abba()
{
int x = 0;
char a;
while ((scanf_s("%c", &a) == 1) && (a == 'a' || a == 'b')) {
switch (x) {
case 0:
if (a == 'a')
x = 1;
break;
case 1:
if (a == 'b')
x = 2;
break;
case 2:
if (a == 'b')
x = 3;
else
x = 1;
break;
case 3:
if (a == 'b')
x = 0;
else {
puts("abba is found !");
x = 4;
}
break;
}
}
}
Upvotes: 1
Views: 47
Reputation: 12732
This is the state machine for your code.
As you see there are 4 states.
Explanation for the each states
- state 0 - If you receives
char a
you move to state 1 else you stay in the state 0.- state 1 - If you receives
char b
you move to state 2 else you stay in the state 1.- state 2 - If you receives
char b
you move to state 3 else you go back to state 1 from there again you need to readbb
to reach state 3.- state 3 - If you receives
char a
you read completeabba
else you need to read the input from the beginning.
Upvotes: 3