LEX Code that accepts the string with 0 only
In this article, we will discuss the overview of the LEX Code that accepts the string with 0 only. And will implement with LEX code also, we will understand the approach. Let’s discuss it one by one.
Problem Overview :
LEX Code that accepts the string with 0 only.
Example –
Input : 00 Output : Accepted Input : 1000 Output : Invalid Input : 23ab Output : Invalid Input : ab345 Output : Invalid Input : 00000 Output : 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.
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 :
C
%{ %} %s A DEAD // logic for dead state %% <INITIAL>0 BEGIN A; <INITIAL>[^0\n] BEGIN DEAD; <INITIAL>\n BEGIN INITIAL; { printf ( "Not Accepted\n" );} // Initial node - Accepted <A>0 BEGIN A; <A>[^0\n] BEGIN DEAD; <A>\n BEGIN INITIAL; { printf ( "Accepted\n" );} // Invalid Case <DEAD>[^\n] BEGIN DEAD; <DEAD>\n BEGIN INITIAL; { printf ( "Invalid\n" );} %% // Method - yywrap int yywrap() { return 1; } // main method int main() { printf ( "Enter String\n" ); // called yylex method yylex(); return 0; } |
Output :
Please Login to comment...