LEX Code that accepts the string with 0 only
Last Updated :
23 Jul, 2021
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
%%
<INITIAL>0 BEGIN A;
<INITIAL>[^0\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; { printf ( "Not Accepted\n" );}
<A>0 BEGIN A;
<A>[^0\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 :
Share your thoughts in the comments
Please Login to comment...