How to use GOTO in C to implement finite automata?

Asked

Viewed 670 times

6

It’s my first time using goto in programming and I made a simple code here to try to implement the automato (must have much better modes), but my code is crashing at the time of running, I do not know if it is a misuse of GOTO on my part, could give me a help?

If anyone has any tips on how I can improve my implementation, I would also appreciate it very much.

Follows the automaton:

imagem

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

int main(){

char str[80];
int count = 0, erro =0;
printf ("\nType your data entry: ");
scanf ("%79s",str);
int i;
int tam= strlen(str);   
printf("%d", tam);
printf("\nSTRING LIDA: ");

for (i =0; i<tam; i++){
    printf("%c", str[i]);
}



i=0;

goto Q0;


Q0:
    if (i == tam){
        printf("\n\nERROEstado q0 nao e final\n\n");
        erro++;
        goto FINAL;
    }
    if(str[i] == 'a'){
        goto Q1;
        i++;
    }
    if (str[i] == 'b'){
        goto Q2;
        i++;    
    }

Q1:
    if (i == tam){
        printf("\n\nERROEstado q1 nao e final\n\n");
        erro++;
        goto FINAL;
    }
    else if(str[i] == 'a'){
        goto Q0;
        i++;
    }
    else if (str[i] == 'b'){
        goto Q3;
        i++;    
    }

Q2:
    if (i == tam){
        printf("\n\nERROEstado q2 nao e final\n\n");
        erro++;
        goto FINAL;
    }
    else if(str[i] == 'a'){
        goto Q3;
        i++;
    }
    else if (str[i] == 'b'){
        goto Q0;
        i++;    
    }   

Q3:
    if (i == tam){
        goto FINAL;
    }
    else if(str[i] == 'a'){
        goto Q2;
        i++;
    }
    else if (str[i] == 'b'){
        goto Q1;
        i++;    
    }   


FINAL:
    if(erro == 0){
        printf("\n\nEntrada aceita!\n\n");
    }
    else if(erro > 0){
        printf("\n\nERRO: Entrada não aceita\n\n");
    }

return 0;
}

1 answer

4

        goto Q3;
        i++;

Your i++ will never be executed, for they are after the goto

  • The delay is great here. Thank you! I hadn’t noticed

  • 1

    Although it seems like a silly problem, I find this question and answer very interesting, because it is something that many confuse and both will help other people ;) +1 for the two.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.