Skip to content
Related Articles

Related Articles

Improve Article

YACC program to recognize string with grammar { anbn | n≥0 }

  • Last Updated : 08 May, 2019

Problem: Write YACC program to recognize string with grammar { anbn | n≥0 }.

Explanation:
Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.

Examples:

Input: ab
Output: valid string

Input: aab
Output: invalid string

Input: aabb
Output: valid string

Input: abb
Output: invalid string

Input: aaabbb
Output: valid string 

Lexical Analyzer Source Code :




%{
   /* Definition section */
  #include "y.tab.h"
 %}
  
/* Rule Section */
 %%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
.  {return yytext[0];}
%%
  
int yywrap() 
 
  return 1; 
 

Parser Source Code :






%{
   /* Definition section */
   #include<stdio.h>
   #include<stdlib.h>
%}
  
%token A B NL
  
/* Rule Section */
%%
stmt: S NL  { printf("valid string\n");
              exit(0); }
;
S: A S B |
;
%%
  
int yyerror(char *msg)
 {
  printf("invalid string\n");
  exit(0);
 }
  
//driver code 
main()
 {
  printf("enter the string\n");
  yyparse();
 }

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 :