Friday, July 29, 2011

Recognize if-else, while and do-while

Share Orkut


Lex Program


%{
#include "y.tab.h"
%}
DIGIT   [0-9]+
ID     [a-zA-Z][a-zA-Z0-9]*
OP    "+"|"-"|"*"|"/"|"%"|"=="|">"|"<"|">="|"="|"<="|"--"|"++"|"!="
OTHR     ";"|"+"|"("|")"|"{"|"}"
ERR     [0-9][a-zA-Z0-9]*
%%
"if"     { return IF; }
"while" { return WHILE; }
"do"    { return DO; }
"else"    { return ELSE; }
{DIGIT} { return DIGIT; }
{ID}    { return ID; }
{ERR}    { return ERR; }
{OP}    { return OPERATOR; }
{OTHR}  { return (int) yytext[0]; }
\n
.
%%
int main()
{
         char inp[20];
         printf("Enter the input file name:-  ");
         scanf("%s",inp);
         yyin=fopen(inp,"r");
         callParser();
         fclose(yyin);
         return 0;
}

Yacc Program


%{
#include <stdio.h>
void callParser();
int if_count=0;
int while_count=0;
int do_count=0;
%}
%token DIGIT ID IF ELSE WHILE DO OPERATOR ERR
%left IF ELSE WHILE DO
%%
COMMANDS: /* empty */
           |COMMANDS WHILE_STMT { while_count++; }
           |COMMANDS IF_STMT { if_count++; }
           |COMMANDS DO_STMT { do_count++; }
       |error
;
WHILE_STMT: WHILE COND ';'
       | WHILE COND '{' STMTS '}'
       | WHILE COND COMMANDS
;
IF_STMT: IF COND ';'
       | IF COND COND ';'
       | IF COND '{' STMTS '}' 
       | IF COND COND ';' ELSE COND ';'
       | IF COND COND ';' ELSE '{' STMTS '}'
       | IF COND '{' STMTS '}' ELSE COND ';'
       | IF COND '{' STMTS '}' ELSE '{' STMTS '}'
       | IF COND COMMANDS ELSE COND ';'
       | IF COND COMMANDS ELSE '{' STMTS '}'
       | IF COND COND ';' ELSE COMMANDS
       | IF COND '{' STMTS '}' ELSE COMMANDS
;
DO_STMT: DO COND ';' WHILE COND ';'
       | DO '{' STMTS '}' WHILE COND ';'
       | DO COMMANDS WHILE COND ';'
;
STMTS: STMTS COND ';'
       | COND ';'
       | STMTS COMMANDS
       |
;
COND: COND OPERATOR COND
       | OPERATOR COND
       | COND OPERATOR
       | ID
       | DIGIT
       | '(' COND ')'
;
%%
void callParser(){
         yyparse();
         printf("No of while statments %d\n",while_count);
         printf("No of if statments %d\n",if_count);
         printf("No of do while statments %d\n",do_count);
}
int yywrap()
{
         return 1;
}
int yyerror(char *mes) {
        return 0;
}

Thursday, July 28, 2011

Arithematic calculator using lex and yacc

Share Orkut


Lex Program


%{
#include <stdio.h>
#include "y.tab.h"
%}
number        [0-9]+
flot         [0-9]*"."[0-9]+
op        "+"|"-"|"*"|"/"|"("|")"|"^"|"%"
%%
{number} {    yylval.fvalue=atof(yytext); return number;    }
{flot} {    yylval.fvalue=atof(yytext); return number;    }
{op}    {    return (int) yytext[0];    }
\n      { return(0); }
.    { return err; }
%%

Yacc Program

%{
#include <stdio.h>
#include <math.h>
int f=0;
float result;
%}
%union {
     float fvalue;
     char *string;
};
%token <fvalue> number
%token <string> err
%type <fvalue> exp
%left '-' '+'
%left '*' '/'
%left NEG
%right '^'  
%%
input:    /* empty string */
          | input exp {result=$2;}
         | error {f=1;}
       ;
exp:     exp '+' exp             { $$ = $1 + $3;   }
           | exp '-' exp             { $$ = $1 - $3;    }
           | exp '*' exp             { $$ = $1 * $3;    }
           | exp '/' exp             { $$ = $1 / $3;    }
           | '-' exp  %prec NEG      { $$ = -$2;        }
           | exp '^' exp             { $$ = pow ($1, $3); }
           | '(' exp ')'             { $$ = $2;         }
       | number                  { $$ = $1;         }
     ;
%%
int main()
{
         printf("\nEnter an arithmetic expression:\n\n");
         yyparse();
         if(f==0)
            printf("Result %f\n",result);
         else
            printf("Invalid Expression\n");
         return 0;
}
int yywrap()
{
         return 1;
}
int yyerror(char *mes) {
        return 0;
}

Wednesday, July 27, 2011

Arithematic Calculator

Share Orkut
%{
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#define YYSTYPE double
%}
%token number
%left '-' '+'
%left '*' '/'
%right '^'
%right NEG
%%
input: /* empty string */
    | input exp '\n'{printf("Result %lf\n",$2);}
    | error '\n'{printf("Invalid Expression\n",$2);}
;
exp: exp '+' exp { $$ = $1 + $3; }
    | exp '-' exp { $$ = $1 - $3; }
    | exp '*' exp { $$ = $1 * $3; }
    | exp '/' exp { $$ = $1 / $3; }
    | '-' exp %prec NEG { $$ = -$2; }
    | exp '^' exp { $$ = pow ($1, $3); }
    | '(' exp ')' { $$ = $2; }
    | number { $$ = $1; }
;
%%
yylex()
{
    char c;
    while((c=getchar())==' ');
    if(isdigit(c)){
      ungetc(c,stdin);
       scanf("%lf",&yylval);
   return number;
   }
    return c;
}
int main()
{
    printf("\nEnter an arithmetic expression:\n\n");
    yyparse();
    return 0;
}
int yywrap()
{
    return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}

Recognize arithematic expression

Share Orkut


Lex program

%{
#include <stdio.h>
#include "y.tab.h"
%}
number        [0-9]+
flot         [0-9]*"."[0-9]+
identifier    [a-zA-Z][a-zA-Z0-9]*
errr     [0-9][a-zA-Z0-9]*
%%
{number} {    return number;    }
{flot} {    return number;    }
{identifier} {    return identifier;    }
{errr} {    return err; }
[ \t]+
\n  {    return(0); }
.    {    return (int) yytext[0];}
%%


Yacc program

%{
#include <stdio.h>
int f=0;
%}
%token number identifier err
%%
input:    /* empty string */
          | input exp
       |error {f=1;}
       ;
exp:      number
       |identifier
           | exp '+' exp            
           | exp '-' exp           
           | exp '*' exp            
           | exp '/' exp            
           | '-' exp 
           | exp '^' exp  
           | '(' exp ')'
     ;
%%
int main()
{
         printf("\nEnter an arithmetic expression:\n\n");
         yyparse();
         if(f==0)
            printf("Valid Expression \n");
         else
            printf("Invalid Expression\n");
         return 0;
}
int yywrap()
{
           return 1;
}
int yyerror(char *mes) {printf("%s\n", mes);}

Recognize (0+1)*000(0+1)*

Share Orkut


%{
#include <stdio.h>
int count=0;
%}
str     [0-1]*"000"[0-1]*
err     [a-zA-Z0-9]+
%%
{str} {    count++; }
{err}
%%
int main()
{
       yylex();
       printf("The pattern (0+1)*000(0+1)* found %d times \n",count);
}
int yywrap()
{
       return 1;
}

Recognize aa(a+b)*bb

Share Orkut


%{
#include <stdio.h>
int count=0;
%}
str     "aa"[ab]*"bb"
err     [a-zA-Z0-9]+
%%
{str} {    count++; }
{err}
%%
int main()
{
       yylex();
        printf("The pattern aa(a+b)*bb found %d times \n",count);
}
int yywrap()
{
        return 1;
}

Thursday, July 14, 2011

Implement (a+b+c)*abc using transition table

Share Orkut


#include<stdio.h>
#include<string.h>
int main()
{
     char str[50],input[15],inpstate[15],outstate[15],state='A';
     int i=0,j;
     strcpy(input,"abcabcabcabc");
     strcpy(inpstate,"AAABBBCCCDDD");
     strcpy(outstate,"BAABCABADBAA");
     printf("\nEnter the string:-  ");
     gets(str);
     while(str[i]!='\0')
     {
          for(j=0;j<12;j++){
         if(inpstate[j]==state && input[j]==str[i]){
              state=outstate[j];
              break;
          }
           }
          if(j==12){
          state='E';
          break;
        }
        i++;
     }
     if(state=='D')
          printf("\nValid String \n");
     else
          printf("\nInvalid String \n");
     return 0;
}

Count statements, identifiers, operators, keywords, integers

Share Orkut
%{
#include <stdio.h>
int no_of_stat=0;
int no_of_id=0;
int no_of_ar=0;
int no_of_re=0;
int no_of_key=0;
int no_of_int=0;
%}
digit [0-9]+
key "int"|"float"|"while"|"if"|"printf"|"for"
id [a-zA-Z][a-zA-Z0-9]*
arop "+"|"-"|"*"|"/"|"%"|"++"|"--"
relop "=="|">"|">="|"<="|"!="|"<"
semi ";"[ ]*"\n"

%%
{digit} { no_of_int++; }
{key} { no_of_key++; }
{id} { no_of_id++; }
{arop} { no_of_ar++; }
{relop} { no_of_re++; }
{semi} { no_of_stat++; }
.
%%
int main()
{
   char inp[20];
    printf("Enter the input file name ");
    scanf("%s",inp);
    yyin=fopen(inp,"r");
    yylex();
    printf("\n no of C statements:- %d",no_of_stat);
    printf("\n no of identifiers:- %d",no_of_id);
    printf("\n no of arithmetic operators :- %d",no_of_ar);
    printf("\n no of relational operators:- %d",no_of_re);
    printf("\n no of keywords:- %d",no_of_key);
    printf("\n no of integers:- %d\n",no_of_int);
}
int yywrap()
{
    return 1;
}

Check for keywords, identifiers, numbers and operators

Share Orkut
%{
#include <stdio.h>
char output[500];
%}
digit [0-9]+
flot [0-9]*"."[0-9]+
key "int"|"float"|"while"|"if"|"printf"
id [a-zA-Z][a-zA-Z0-9]*
op "+"|"-"|"*"|"/"|"%"|"=="|">"|">="|"="
err [0-9][a-zA-Z0-9]*
%%
{digit} { sprintf(output,"%snumber ",output); }
{flot} { sprintf(output,"%sflonumber ",output); }
{key} { sprintf(output,"%skeyword ",output); }
{id} { sprintf(output,"%sidentifier ",output); }
{op} { sprintf(output,"%soperator ",output); }
{err} { sprintf(output,"%sinvalid ",output); }
[ \t\n{}();:,]+ { sprintf(output,"%s%s",output,yytext); }
%%
int main()
{
    char inp[20];
    printf("Enter the input file name ");
    scanf("%s",inp);
    yyin=fopen(inp,"r");
    yylex();
    printf("%s",output);
}
int yywrap()
{
    return 1;
}

Wednesday, July 6, 2011

Binary number with two concecutive zeros

Share Orkut

DFA


#include<stdio.h>
int main(){
  int i=0,state=0;
 char str[100];
   printf("\nEnter a binary number:- ");
   gets(str);
 while(str[i]!='\0'){
  switch(str[i]){
    case '0':if(state!=2)
    state++;
     break;
    case '1':if(state==1)
    state=0;
     break;
    default:state=5;
     i=strlen(str)-1;
  }
  i++;
 }
 if(state==2)
  printf("\nValid String\n");
 else 
  printf("\nIn Valid String\n");
 return 0;
}

Implement (a/b)*abb using DFA

Share Orkut

DFA


#include<stdio.h>
int main(){
  int i=0,state=0;
 char str[100];
   printf("\nEnter the string:- ");
   gets(str);
 while(str[i]!='\0'){
  switch(str[i]){
    case 'a':state=1;
     break;
    case 'b':if(state!=0)
    state=(state+1)%4;
     break;
    default:state=5;
     i=strlen(str)-1;
  }
  i++;
 }
 if(state==3)
  printf("\nValid String\n");
 else 
  printf("\nIn Valid String\n");
 return 0;
}