Skip to content
Related Articles

Related Articles

Improve Article

DFA in LEX code which accepts strings ending with 11

  • Last Updated : 22 May, 2019

Prerequisite: Designing Finite Automata
Problem: Design a LEX code to construct a DFA which accepts the language: all the strings ending with “11” over inputs ‘0’ and ‘1’.

Examples:

Input: 100011 
Output: Accepted

Input: 100101
Output: Not Accepted

Input: asdf
Output: Invalid 

Approach:
LEX provides us with an INITIAL state by default. So in order to make a DFA, use this as the initial state of the DFA. Now we define three more states A, B and DEAD where DEAD state would be use if encounter a wrong or invalid input. When user input invalid character, move to DEAD state and print message “INVALID” and if input string ends at state B then display a message “Accepted”. If input string ends at state INITIAL and A then display a message “Not Accepted”.





Note:
To compile a LEX program, user need a UNIX system and flex which can be installed using sudo apt-get install flex. With all the above specification open UNIX terminal and do the following:



  1. Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file.
  2. Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file.
lex lextest
cc lex.yy.c -lfl 

LEX Code:




%{
%}
  
%s A B DEAD
  
%%
<INITIAL>1 BEGIN A;
<INITIAL>0 BEGIN INITIAL;
<INITIAL>[^01\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}
  
<A>1 BEGIN B;
<A>0 BEGIN INITIAL;
<A>[^01\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Not Accepted\n");}
  
<B>1 BEGIN B;
<B>0 BEGIN INITIAL;
<B>[^01\n] BEGIN DEAD;
<B>\n BEGIN INITIAL; {printf("Accepted\n");} 
  
<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");} 
  
%%
  
int main()
{
    printf("Enter String\n");
    yylex();
return 0;
}

Output:

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :