Problem Overview –
Design a DFA in LEX Code that accepts the string having even binary number over input alphabet {0,1}.
Example –
Input : 1010 Output: Accepted Input : 1001 Output: Not Accepted Input: 23ab Output:Invalid Input:ab345 Output:Invalid Input:010101 Output:Not Accepted
Approach :
LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define two more states: A, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at A then display the message “Accepted”. Else if the input string ends at state INITIAL then displays the message “Not Accepted”.
Note –
To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.
For example- filename.l
Then after saving the program closes the lex file and then open the terminal and write the following commands as follows.
lex filename.l cc lex.yy.c ./a.out
LEX CODE :
%{ %} %s A DEAD %% <INITIAL>0 BEGIN A; <INITIAL>1 BEGIN INITIAL; <INITIAL>[^01\n] BEGIN DEAD; <INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");} <A>0 BEGIN A; <A>1 BEGIN INITIAL; <A>[^01\n] BEGIN DEAD; <A>\n BEGIN INITIAL; {printf("Accepted\n");} <DEAD>[^\n] BEGIN DEAD; <DEAD>\n BEGIN INITIAL; {printf("Invalid\n");} %% int yywrap() { return 1; } int main() { printf("Enter String\n"); yylex(); return 0; }
Output :
Enter String 1100 Accepted 1010 Accepted 0001 Not Accepted abc Invalid 0101 Not Accepted