c program to find e-closure of NFA

program to find e-closure in an NFA. States are represented as q0,q1,q2 etc. The input symbols are {0,1,e}.The transition table is read from the file automta.txt
***************************************
#include<stdio.h>
#include<string.h>

char result[20][20], copy[3], states[20][20];

void add_state(char a[3], int i) {

  strcpy(result[i], a);

}

void display(int n) {

  int k = 0;

  printf("\n  Epsilon closure of %s = { ", copy);

  while (k < n) {

    printf(" %s", result[k]);

    k++;

  }

  printf(" }\n");

}

int main() {

  FILE * INPUT;

  INPUT = fopen("automata.txt", "r");

  char state[3];

  int end, i = 0, n, k = 0;

  char state1[3], input[3], state2[3];

  printf("\n Enter the no of states: ");

  scanf("%d",&n);

  printf("\n Enter the states max =20 \n");

  for (k = 0; k < n; k++) {

    scanf("%s", states[k]);

  }

  for (k = 0; k < n; k++) {

    i = 0;

    strcpy(state, states[k]);

    strcpy(copy, state);

    add_state(state, i++);

    while (1) {

      end = fscanf(INPUT, "%s%s%s", state1, input, state2);

      if (end == EOF) {

        break;

      }

      if (strcmp(state, state1) == 0) {

        if (strcmp(input, "e") == 0) {

          add_state(state2, i++);

          strcpy(state, state2);

        }

      }

    }

    display(i);

    rewind(INPUT);

  }

  return 0;

}

Execution
****************
$ cat automata.txt
q0 0 q0
q0 1 q1
q0 e q1
q1 1 q2
q1 e q2

$ gcc e-closure.c
$ ./a.out

Enter the no of states(max 20): 3

 Enter the states
q0
q1
q2

  Epsilon closure of q0 = {  q0 q1 q2 }

  Epsilon closure of q1 = {  q1 q2 }

  Epsilon closure of q2 = {  q2 }


Comments

Popular posts from this blog

KTU Compiler Lab CSL411 - Dr Binu V P

lexical analyzer for a c program

13.Precedence and conflict resolution in yacc