Skip to content
Related Articles
Open in App
Not now

Related Articles

LEX Code that accepts the string with 0 only

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 23 Jul, 2021
Improve Article
Save Article

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 :


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

LEX Code :


// logic for dead state  
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}
// Initial node - Accepted
<A>[^0\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Accepted\n");}
// Invalid Case
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");}
// Method - yywrap  
int yywrap()
return 1;
// main method
int main()
   printf("Enter String\n");
  // called yylex method
return 0;

Output :

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!