Lex & Yacc : Acceptance of string

Ques : Write a lex and yacc program to accept strings over {0,1} from the set {00,0000,000000….. , 11,1111,111111…..}

// (yacc file)
%{
#include<stdlib.h>
#include<stdio.h>
void yyerror(char *s);
%}
%token Z O
%%
S : S A {printf("Accepted ");}
| A ;
A : Z Z
| O O ;
%%
int main()
{
yyparse();
}
void yyerror(char *s)
{
fprintf(stdout,"\nNot Accepted !\n");
}

// Lex File

%{
#include<stdio.h>
#include<stdlib.h>
#include"y.tab.h"
extern int yylval;
%}
%%
0 {yylval=0;return Z;}
1 {yylval=1;return O;}
[ \t] {;}
\n return 0;
. return yytext[0];
%%

Output :-
00
Accepted !
0101
Not Accepted !

Leave a comment