paiiiin
paiiiin

Reputation: 7

Can somebody explain how this state machine program works?

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

Answers (1)

kiran Biradar
kiran Biradar

Reputation: 12732

This is the state machine for your code. enter image description here

As you see there are 4 states.

Explanation for the each states

  1. state 0 - If you receives char a you move to state 1 else you stay in the state 0.
  2. state 1 - If you receives char b you move to state 2 else you stay in the state 1.
  3. 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 read bb to reach state 3.
  4. state 3 - If you receives char a you read complete abba else you need to read the input from the beginning.

Upvotes: 3

Related Questions