/* 6a. Write a LEX program to recognize a valid arithmetic expression. Count number of operators present and print them seperately. */

%{
/* No. of operators and operands */
int nop=0,noprnd=0,top=-1,stack[20];
%}

%%
[0-9]*|[a-zA-Z]* noprnd++; /* Increment no. of operand */
[+-/*%] nop++;                /* Increment no. of operator */
"(" { stack[++top]='(';}
")" { if((stack[top]='(')&&(top!=-1)) top--; }
%%

#include"stdio.h"
int main()
{
    printf("\n*** Enter an expression ***\n");
    yylex();
    if ((nop != (noprnd - 1)) || ( top==-1))
        printf("\nIt's an INVALID statement");
    else
    {
        printf("\nIt's a VALID statement");
        printf("\nNumber of operators = %d",nop);
    }
    return 0;
}


 

/* 6b. Write a YACC program to identify a language a^n b, where n>0 */

%token A
%token B

%%

pattern:
    |pattern '\n'
    |pattern series '\n'
;

series:
    B
    |seriesa B
;

seriesa: 
    A
    |seriesa A
;

%%

#include<stdio.h>
main()
{
    yyparse();
}
yylex()
{
    int c;
    while((c=getchar())=='\t'||c==' ');
        if(c=='a')
            return A;
    if(c=='b')
        return B;
}
yyerror(char *s)
{
    printf("\n%s : a^nb, n>=0\n",s);
}