Wednesday 24 February 2016

Experiment No - 01




PROGRAM: Implementation of Symbol Table
#include<stdio.h>
#include<string.h>ruct symboltable
{
int position;
char name[20];
char type[20];
int allst;
}s[20];
int main()
{
int i=0,p=0,n,j,k;
char input[20],type[20];
char dt[5][20]={"int","char","float","double","long"};
FILE *fp;
fp=fopen("input.txt","r");
fscanf(fp,"%s",input);
while(strcmp(input,"EOF")!=0)
{
for(j=0;j<5;j++)
{
if(strcmp(input,dt[j])==0)
{
strcpy(type,input);
fscanf(fp,"%s",input);
while(strcmp(input,";")!=0)
{
if(strcmp(input,",")!=0)
{
p++;
s[p].position=++i;
strcpy(s[p].name,input);
strcpy(s[p].type,type);
fscanf(fp,"%s",input);
}
if(strcmp(input,";")!=0)
fscanf(fp,"%s",input);
}
fscanf(fp,"%s",input);
}
}
fscanf(fp,"%s",input);
}
n=i+1;
for(k=1;k<n;k++)
{
if(strcmp(s[k].type,"int")==0)
s[k].allst=2;
else if((strcmp(s[k].type,"float")==0)||(strcmp(s[k].type,"double")==0))
s[k].allst=4;
else if(strcmp(s[k].type,"char")==0)
s[k].allst=1;
else if(strcmp(s[k].type,"long")==0)
s[k].allst=8;
}
printf("\n SYMBOL TABLE FOR IDENTIFIER");
printf("\n-------------------------------------------");
printf("\nPOSITION\tNAME\tTYPE\tALLOCATEDSTORAGE\tADDRESS");
printf("\n-------------------------------------------------------------------------");
for(k=1;k<n;k++)
{
printf("\n%d\t\t\t%s\t%s\t\t%d\t\t%d",s[k].position,s[k].name,s[k].type,s[k].allst,1000+k*s[k].allst);                                        
}
}
INPUT:
void main()
{
int a ;
float b ;
int c ;
c = a + b ;
}
EOF
OUTPUT:
$ ./a.out

 SYMBOL TABLE FOR IDENTIFIER
-------------------------------------------
POSITION        NAME    TYPE    ALLOCATEDSTORAGE      ADDRESS
------------------------------------------------------------------------------------
1                       a               int                         2                            1002
2                       b              float                      4                            1008
3                       c              int                           2                           1010

Experiment No - 02




 Develop a lexical analyzer to recognize a few patterns in c
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
FILE *fp;
int i,n;
char input[10];
char key[11][10]={"include","void","main()","int","char","float","if","else","while","do","for"};
char op[11][2]={"+","<",">","/","-","*","&","^","%","!","="};
char symbol[11][2]={",",")","(","?","{","}","[","]","#",";",":"};
clrscr();
fp=fopen("input.c","r");
fscanf(fp,"%s",input);
while(strcmp(input,"EOF")!=0)
{
for(i=0;i<11;i++)
{
if(strcmp(input,key[i])==0)
{
goto e;
}
}
for(i=0;i<11;i++)
{
if(strcmp(input,op[i])==0)
{
printf("<operator,%s>\n",input);
goto e;
}
}
for(i=0;i<11;i++)
{
if(strcmp(input,symbol[i])==0)
{
printf("<symbol,%s>\n",input);
goto e;
}
}
if((input[0]>='a' && input[0]<='z')||(input[0]>+'A'&& input [0]<='Z'))
{
n=strlen(input);
for(i=1;i<n;i++)
{


if((input[i]>='a'&&input[i]<='z')||(input[i]>='A'&&input[i]<='Z')||(input[i]>='0'&&input[i]<='9'))
continue;
else
{
printf("<\n Invalid identifiers,%s \n",input);
goto e;
}
}
if(i==n)
printf("<Identifiers,%s>\n",input);
}
else
printf("Invalid Identifiers\n");
e:
fscanf(fp,"%s",input);
}
getch();
}

INPUT:
void main()
{
int a,b;
float d;
d = a+b;
}
EOF
OUTPUT:
<symbol,{>
<Identifiers,a>
<symbol,;>
<Identifiers,b>
<symbol,;>
<Identifiers,double>
<Identifiers,c>
<symbol,;>
<Identifiers,d>
<symbol,;>
<Identifiers,c>
<operator,=>
<Identifiers,a>
<operator,+>
<Identifiers,b>
<symbol,;>
<symbol,}>

Tuesday 23 February 2016

Experiment No : 08





8. Implement any one storage allocation strategies(Heap,Stack,Static)

Heap storage allocation strategy

/************************************************************
Program to perform various operations such as creation, insertion, deletion, display of heap
*************************************************************/
#include"stdio.h"
#include"conio.h"
#include"stdlib.h"
#define TRUE 1
#include FALSE 0

typedef struct Heap
{
int data;
struct Heap *next;
}node;

node *create();

void main()
{
/*local declarations*/
int choice,val;
char ans;
node *head;
void display(node *);
node *search(node *,int);
node *insert(node *);
void dele(node **);
head=NULL;
do
{
clrscr();
printf(“\n Program to perform various operations on heap
using dynamic memory management”);
printf (“\n1.Create”):
printf (“\n2.Display”):
printf (“\n3.Insert an element in a list”);
printf (“\n4.Delete an element from list”);
printf (“\n5.Quit”);
printf (“\n Enter Your Choice(1-5)”);
scanf(“%d,&choice”);
switch(choice)
{
case 1:head=create();
break;
case 2:display(head);
break;
case 3:head=insert(head);
break;
case 4:dele(&head);
break;
case 5:exit(0);
default:clrscr();
printf(“Invalid Choice,Try again”);
getch();
}
}while(choice!=5);
}

/*The create function creates a list of allocated node
*Input:None
*Output:Retyurns a pointer to head of list
*Parameter Passing Methopd:Node
**/

node *create()
{
node *temp,*new,* head;
int val,flag;
char ans=’y’;
node *get_node();
temp=NULL;
flag=TRUE;
/*flag to indicate whether a new node is created for the first time or not*/
do
{
printf(“\n Enter the Element”);
scanf(“%d”,&val);
/*allocate new node*/
new =get_node();

if(new==NULL)
printf(“\n Memory is not allocated”);
new-> data=val;
if (flag==TRUE)/* Executed only for the first time*/
{
head=new;
temp=head; /*head is the first node in the heap*/
flag=FALSE;
}
else
{
/*temp keeps track of the most recently created node*/

temp->next=new;
temp=new;
}
printf(\nDo you want to enter more elements?(y/n)”);
ans=getch();
}while(ans= = ‘y’);

printf(“\nThe list is created”);
getch();
clrscr();
return head;
}

node *get_node()
{
node *temp;
temp=(node*)malloc(sizeof(node));
//using the mem. Allocation function
temp->next=NULL;
return temp;
}

/*
*The display function
*Input:Address of the first node of the list
*Output:Displays the list of allocated nodes
*Parameter Passing Method : call by value
*Called by main
**/

void display(node*head)
{
node *temp;
temp=head;
if(temp= =NULL)
{
printf(“\n The list is empty\n”);
getch();
clrscr();
return;
}
while(temp!= NULL)
{
printf(“%d->”,temp-> data);
temp=temp->next;
}
print(“NULL”);
getch();
clrscr();
}

/*
*The search function
*Input: Address of the starting node and the element which is *to be searched
*Output:Searches for the element in list
*If found returns pointer to that node Otherwise NULL
*Parameter passing Method:call by value
*Called by:main
*Calls:None
**/

node *search(node *head,int key)
{
node*temp;
int found;
temp=head;
if (temp= =Null)
{
printf(“The linked list is empty\n”);
getch();
clrscr();
return NULL;
}

found=FALSE;
While(temp!= NULL && found= =FALSE)
{
if(temp->data != key)
temp = temp->next;
else
found = True;
}

if(found == TRUE)
{
printf(“\n The Elements is present in the list”\n);
getch();
return temp;
}
else
printf(“\n The Element is not present in the list\n”);
getch();
return NULL;
}

/*
*The insert function
*Input: Address of starting node of the list
*Output:inserts element into the list
*Parameter Passing Methods: call by value
*Called by : main
*Calls : search()
**/

node *insert(node *head)
{
int choice;
node *insert_head(node*);
void insert_after(node*);
void insert_last(node*);
printf(“\n”1.Insert a node as a head node”);
printf(“\n”1.Insert a node as a last node”);
printf(“\n”1.Insert a node as at the intermediate position in the list ”);
printf(“\n”1.Enter your choice for insertion of node ”);
scanf(“%d”,&choice);
switch(choice)
{
case 1:head = insert_head(head);
break;
case2:insert_last(head);
break;
case2:insert_after (head);
break;
}
return head;
}

/*Insertion of node at first position*/

node *insert_head(node*head)
{
node *New,*temp;
New = get_node();
printf (“\n Enter the element which you want to insert ”);
scanf(“%d”,&New->data);
if(head == NULL)
head = New;
else
{
temp=head;
New->next = temp;
head= New;
}
return head;
}

/*Insertion of node at last position*/

void insert_last(node *head)
{
node *New,*temp;
New = get_node();
printf (“\n Enter the element which you want to insert ”);
scanf(“%d”,&New->data);
if(head == NULL)
{
head = New;
}
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=New;
New->next=NULL;
}
}

/*Insertion of node at intermediate position*/

void insert_after(node *head)
{
int key;
node *New,*temp;
New = get_node();
printf(“Enter the element after which you want to insert ”);
scanf(“%d”,&key);
temp=head;

do
{
if(temp->data==key)
{
printf (“Enter element which you want to insert ”);
scanf(“%d”,&New->data);
New->next=temp->next;
temp->next=New;
return;
}
else
temp=temp->next;
}while(temp!=NULL);
}

/*
*The get prev function
*Input: Address of starting node and the elemnt to be *searched
*Output:looks for the element in the list
*If found returns pointer to the previous node otherwise NULL
*Parameter Passing Methods: call by value
*Called by : dele()
*Calls : none
**/

node *get_prev(node *head,int val)
{
node*temp.*prev;
int flag;
temp = head;
if(temp == NULL)
return NULL;
flag = FALSE;
prev = NULL;
while(temp!=NULL && !flag)
{
if(temp->data!=val)
{
prev = temp;
temp = temp->next;
}
else
flag = TRUE;
}

if(flag) /*if Flag is true*/
return prev;
else
return NULL;
}





/*
*The get prev function
*Input: Address of starting node and the elemnt to be *searched
*Output:looks for the element in the list
*If found returns pointer to the previous node otherwise NULL
*Parameter Passing Methods: call by value
*Called by : dele()
*Calls : none
**/

void dele(node **head)
{
int key;
node *New,*temp;
temp=*head;
if (temp== NULL)
{
printf (“\n The list is empty\n ”);
getch();
clrscr();
return;
}

clrscr();
printf("\nENTER the Element you want to delete:");
scanf("%d".&key);
temp= search(*head,key);
if(temp !=NULL)
{
prev = get_prev(*head,key);
if(prev != NULL)
{
prev ->next = temp-> next;
free(temp);
}
else
{
*head = temp->next;
free(temp); // using the mem. Dellocation function
}
printf(“\n”The Element is deleted\n”);
getch();
clrscr();
}
}








Output:

Program to perform various operations on heap using Dynamic memory management.

1. Create
2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 1

Enter the element: 10

Do you want to enter more elements? (y/n) y

Enter the element:20

Do you want to enter more elements?(y/n)y

Enter the element:30

Do you want to enter more elements?(y/n)n

The List is created


Program to perform various operations on Heap using Dynamic memory management.

1. Create
2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 4

Enter the element you want to delete: 20

The element is present in the list

The element is deleted

Program to perform various operations on Heap using Dynamic memory management.

1. Create
2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 2
10-> 30-> NULL

Experiment No : 05

5) Convert the BNF rules into Yacc form and write code to generate abstract syntax tree.
<int.l>
%{
#include"y.tab.h"
#include<stdio.h> #include<string.h> int LineNo=1; %}
identifier [a-zA-Z][_a-zA-Z0-9]* number [0-9]+|([0-9]*\.[0-9]+)
%%
main\(\) return MAIN; if return IF; else return ELSE;
while return WHILE;
int |
char | float return TYPE; {identifier} {strcpy(yylval.var,yytext); return VAR;} {number} {strcpy(yylval.var,yytext);
return NUM;}
\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
<int.y>
%{
#include<string.h> #include<stdio.h> struct quad { char op[5]; char arg1[10]; char arg2[10];
char result[10];
}QUAD[30];
struct stack { int items[100]; int top; }stk;
int Index=0,tIndex=0,StNo,Ind,tInd; extern int LineNo;
%}
%union
{
char var[10];
}
%token <var> NUM VAR RELOP
%token MAIN IF ELSE WHILE TYPE
%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP
%left '-' '+'
%left '*' '/'
%%
PROGRAM : MAIN BLOCK
;
BLOCK: '{' CODE '}'
;
CODE: BLOCK
| STATEMENT CODE
| STATEMENT
;
STATEMENT: DESCT ';'
| ASSIGNMENT ';'
| CONDST
| WHILEST
;
DESCT: TYPE VARLIST
;
VARLIST: VAR ',' VARLIST
| VAR
;
ASSIGNMENT: VAR '=' EXPR{ strcpy(QUAD[Index].op,"="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,$1); strcpy($$,QUAD[Index++].result);
}
;
EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);}
| EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);}
| EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);}
| EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);}
| '-' EXPR {AddQuadruple("UMIN",$2,"",$$);}
| '(' EXPR ')' {strcpy($$,$2);}
| VAR
| NUM
;
CONDST: IFST{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index); Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
| IFST ELSEST
;
IFST: IF '(' CONDITION ')' { strcpy(QUAD[Index].op,"=="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,"FALSE"); strcpy(QUAD[Index].result,"-1"); push(Index);
Index++;
}
BLOCK { strcpy(QUAD[Index].op,"GOTO"); strcpy(QUAD[Index].arg1,"");
strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
};
ELSEST: ELSE{
tInd=pop(); Ind=pop(); push(tInd);
sprintf(QUAD[Ind].result,"%d",Index);
}
BLOCK{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
};
CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$);
StNo=Index-1;
}
| VAR
| NUM
;
WHILEST: WHILELOOP{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo); Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')' { strcpy(QUAD[Index].op,"=="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,"FALSE"); strcpy(QUAD[Index].result,"-1");
push(Index);
Index++;
}
BLOCK {
strcpy(QUAD[Index].op,"GOTO"); strcpy(QUAD[Index].arg1,""); strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,"-1"); push(Index);
Index++;
}
;
%%
extern FILE *yyin;
int main(int argc,char *argv[])
{
FILE *fp;
int i;
if(argc>1) {
fp=fopen(argv[1],"r");
if(!fp) {
printf("\n File not found");
exit(0); } yyin=fp; } yyparse();
printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t
--------------------"); for(i=0;i<Index;i++)
{
printf("\n\t\t %d\t %s\t %s\t %s\t
%s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result);
}
printf("\n\t\t -----------------------");
printf("\n\n"); return 0; }
void push(int data)
{ stk.top++; if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0); }
stk.items[stk.top]=data;
} int pop() { int data; if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0); }
data=stk.items[stk.top--];

return data; }
void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10])
{
strcpy(QUAD[Index].op,op); strcpy(QUAD[Index].arg1,arg1); strcpy(QUAD[Index].arg2,arg2); sprintf(QUAD[Index].result,"t%d",tIndex++); strcpy(result,QUAD[Index++].result);
} yyerror() {
printf("\n Error on line no:%d",LineNo);
}
Input: $vi test.c main() { int a,b,c; if(a<b) { a=a+b; } while(a<b) { a=a+b; } if(a<=b) { c=a-b; } else { c=a+b;
}
}
Output:
$lex int.l
$yacc –d int.y
$gcc lex.yy.c y.tab.c –ll –lm
$./a.out test.c


___________________________________________________

Experiment No : 04




4. Generate YACC specification for a few syntactic categories.
a) Program to recognize a valid arithmetic expression that usesoperator +, - , * and /.
b) Program to recognize a valid variable which starts with a letterfollowed by any number of letters or digits.
 d)Implementation of Calculator using LEX and YACC


4.Generate YACC specification for a few syntactic categories.
a) Program to recognize a valid arithmetic expression that uses operator +, - , * and /.


Program name:arith_id.l

%{
/* This LEX program returns the tokens for the expression */
#include “y.tab.h”
%}

%%
“=” {printf(“\n Operator is EQUAL”);}
“+” {printf(“\n Operator is PLUS”);}
“-“ {printf(“\n Operator is MINUS”);}
“/” {printf(“\n Operator is DIVISION”);}
“*” {printf(“\n Operator is MULTIPLICATION”);}

[a-z A-Z]*[0-9]* {
printf(“\n Identifier is %s”,yytext);
return ID;
}
return yytext[0];
\n return 0;
%%

int yywrap()
{
return 1;
}


Program Name : arith_id.y

%{
#include
/* This YYAC program is for recognizing the Expression */
%}
%%
statement: A’=’E
| E {
printf(“\n Valid arithmetic expression”);
$$ = $1;
};

E: E’+’ID
| E’-’ID
| E’*’ID
| E’/’ID
| ID
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}

yyerror(char*s)
{
}

Output:

[root@localhost]# lex arith_id.1
[root@localhost]# yacc –d arith_id.y
[root@localhost]# gcc lex.yy.c y.tab.c
[root@localhost]# ./a.out
x=a+b;

Identifier is x
Operator is EQUAL
Identifier is a
Operator is PLUS
Identifier is b


b) Program to recognise a valid variable which starts with a letter
followed by any number of letters or digits.

Program name: variable_test.l

%{
/* This LEX program returns the tokens for the Expression */
#include "y.tab.h"
%}
%%
"int " {return INT;}
"float" {return FLOAT;}
"double" {return DOUBLE;}
[a-zA-Z]*[0-9]*{
printf("\nIdentifier is %s",yytext);
return ID;
}
return yytext[0];
\n return 0;
int yywrap()
{
return 1;
}



Program name: variable_test.y

%{
#include
/* This YACC program is for recognising the Expression*/
%}
%token ID INT FLOAT DOUBLE
%%
D;T L
;
L:L,ID
|ID
;
T:INT
|FLOAT
|DOUBLE
;
%%
extern FILE *yyin;
main()
{
do
{
yyparse();
}while(!feof(yyin));
}
yyerror(char*s)
{
}

Output:

[root@localhost]# lex variable_test.I
[root@localhost]# yacc –d variable_test.y
[root@localhost]# gcc lex.yy.c y.tab.c
[root@localhost]# ./a.out
int a,b;

Identifier is a
Identifier is b[root@localhost]#













c) Program to recognise the gramar(anb where n>=10)
Program name: anb.l

%{
/*Lex Program for anb(n>=10)*/
%}
%%
a {return A;}
b {return B;}
. {return yytext[10];}
\n return('\n');
%%
int yywrap()
{
return 1;
}

Program name:anb.y

%{
/*YACC program for recognising anb(n>=10)*/
%}
%token A B
%%
stmt:A A A A A A A A A A anb'\n'{printf("\n Valid string");
return 0;
}
;
anb:A anb
|A B
;
%%
main()
{
printf("\nEnter some valid string\n");
yyparse();
}

int yyerror(char*s)
{
printf("\nInvalid string\n");
}


Output:

[root@localhost]# lex anb.1
[root@localhost]# yacc -d anb.y
[root@localhost]# gcc lex.yy.c y.tab.c
[root@localhost]# ./a.out


Enter some valid string
aaaaaaaaab

Invalid string
[root@localhost]# ./a.out

Enter some valid string
aaaaaaaaaaab

Valid string [root@localhost]#


d) Implementation of Calculator using LEX and YACC

Program name:calci.l

%{
#include "y.tab.h" /*defines the tokens*/
#include ,math.h.
%}
%%
/*To recognise a valid number*/
([0-9] + |([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval = atof(yytext);
return NUMBER;}
/*For log no | Log no (log base 10)*/
log | LOG {return LOG;}

/*For ln no (Natural Log)*/
ln {return nLOG;}

/*For sin angle*/
sin | SIN {return SINE;}

/*For cos angle*/
cos | COS {return COS;}

/*For tan angle*/
tan | TAN {return TAN;}
/*For memory*/
mem {return MEM;}

[\t] ; /*Ignore white spaces*/

/*End of input*/
\$ {return 0;}

/*Catch the remaining and return a single character token to
the parser*/
\n| return yytext[0];
%%


Program Name : calci.y

%{
double memvar;
%}

/*To define possible symbol types*/
%token NUMBER
%token MEM
%token LOG SINE nLOG COS TAN

/*Defining the precedences and associativity*/
%left ‘-’ ‘+’ /*Lowest precedence*/
%left ‘*’ ‘/’
%right ‘^’
%left LOG SINE nLOG COS TAN /*Highest precence*/

/*No associativity*/
%nonassoc UMINUS /*Unary Minus*/

/*Sets the type for non-terminal*/
%type expression
%%
/*Start state*/
start: statement ‘\n’
| start statement ‘\n’
;

/*For storing the answer(memory)*/
statement: MEM’=’ expression {memvar=$3;}
| expression {printf(“Answer = %g\n”,$1);}
; /*For printing the Answer*/




/*For binary arithmetic operations*/
expression: expression ‘+’ expression {$$ = $1 + $3;}
| expression ‘-’ expression {$$ = $1 - $3;}
| expression ‘*’ expression {$$ = $1 * $3;}
| expression ‘/’ expression
{ /*Tohandle divide by zero case*/
If($3 == 0)
yyerror(“divide by zero”);
else
$$ = $1 / $3;
}
| expression ‘^’ expression {$$ = pow($1,$3);}
;


/*For unary operators*/
expression: ‘-’expression %prec UMINUS {$$ = -$2;}
/*%prec UMINUS signifies that unary minus should have the highest precedence*/
| ‘(’ expression ‘)’ {$$ = $2}
| LOG expression {$$ = log($2)/log(10);}
| nLOG expression {$$ = log($2);}
*/Trigonometric functions*/
| SINE expression {$$ = sin($2 * 3.141592654 / 180);}
| COS expression {$$ = cos($2 * 3.141592654 / 180);}
| TAN expression {$$ = tan($2 * 3.141592654 / 180);}
| NUMBER {$$ = $1;}
| MEM {$$ = $1;}
; /*Retrieving the memory contents*/
%%
main()
{
printf(“Enter the expression:”);
yyparse();
}
int yyerror(char *error)
{
fprintf(stderr,”%s\n”,error);
}


Output:

The output of the program can be obtained by following commands
[root@localhost]]# lex calci.l
[root@localhost]]# yacc –d calci.y
[root@localhost]]# cc y.tab.c lexyy.c –ll –ly –lm
[root@localhost]]# ./a.out

Enter the expression: 2+@
Answer = 4

2 * 2 + 5 / 4
Answer = 5.25

mem = cos 45
sin 45/mem
Answer = 1

ln 10
Answer = 2.

Experiment No : 03




3. Implementation of Lexical Analyzer using Lex Tool
 


%{
/*******************************************************************
Program to obtain tokens from a c program using LEX

*******************************************************************/
int COMMENT = 0;
int cnt = 0;

%}


identifier[a-zA-Z][a-zA-Z0-9]*
%%


#.* {printf("\n%is a PREPROCESSOR DIRECTIVE", yytext);}

int |
float |
char |
double |
while |
for |
do |
if |
break |
continue |
void |
switch |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}


"*/" {COMMENT = 1;}

"*/" {COMMENT = 0;}
cnt++;
}
{identifier}\(if(COMMENT){printf("\n\nFUNCTIONAL\n\t%s",yytext);}
\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}



\} {if(!COMMENT)printf("\nBLOCK ENDS");}


{identifier}(\[0-9]*\])? {if(!COMMENT)printf("\n\t%s is an IDENTIFIER",yytext);}

\".*\" {if(!COMMENT)printf("\n\t% is a STRING",yytext);}

[0-9]+ {if(!COMMENT)printf("\n\t%is a NUMBER",yytext);}

\)(\;)? {if(!COMMENT)printf("\n\t");ECHO;print("\n";)}

\( ECHO;
= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext)}

\+|
\- {if(!COMMENT)printf("\n\t%s is an OPERATOR",yytext);}


\<=|
\>=|
\<|
==|
\> {if(!COMMENT)printf(\n\t%s is a RELATIONAL OPERATOR",yytext);}



|\n


%%
int main(int argc.char**argv)
{
if(argc>1)
{
FILE *file';
file fopen(argv[1]."r");
if(file)
{
printf(“\n Could not open %s”,argv[1];
exit(0);
}
yyin = file;
}
yylex();
printf(“ \n Total number of comments are %d”,cnt);
return 0;
}

int yywrap()
{
return 1;
}



Input File:

#include
#include

double area_of_circle(double r);

int main(int argc,char *argv[])
{
if(argc < 2)
{
printf(“ Usage: %s radius \n”,argv[0]);
exit(1);
}
else
{
/* This is a double line comment */
double radius = atof(argv[1]);
double area = area_of_circle(radius);
printf(“ Area of circle with radius %f = %f \n”,radius,area);
}
return 0;
}
























Output:

[root@localhost]# lex lexp.l
[root@localhost]# gcc lex.yy.c
[root@localhost]# ./a.out area.c

#include
#include
double is a KEYWORD
area is an INDENTIFIER
of is an INDENTIFIER
circle is an INDENTIFIER
(double is a KEYWORD
r is an INDENTIFIER
);

int is a KEYWORD
main is an INDENTIFIER
(int is a KEYWORD
argc is an INDENTIFIER
char is a KEYWORD
argv[] is an INDENTIFIER
)

BLOCK BEGINS
if is a KEYWORD
(argc is an INDENTIFIER
< is a RELATIONAL OPERATOR
2 is a NUMBER
)

BLOCK BEGINS
printf is an INDENTIFIER
(“ Usage: %s radius \n”,is a STRING
argv[0] is an INDENTIFIER
);

exit is an INDENTIFIER
(1 is a NUMBER
);

BLOCK ENDS
else is a KEYWORD


BLOCK BEGINS
double is a KEYWORD
radius is an INDENTIFIER
= is an ASSIGNMENT OPERATOR
atof is an INDENTIFIER
(argv[1]is an INDENTIFIER
);

double is a KEYWORD
area is an INDENTIFIER
= is an ASSIGNMENT OPERATOR
area is an INDENTIFIER
of is an INDENTIFIER
circle is an INDENTIFIER
(radius is an INDENTIFIER
);

printf is an INDENTIFIER
(“Area of circle with radius %f = %f \n”, is a STRING
radius is an INDENTIFIER
area is an INDENTIFIER
);


BLOCK ENDS
return is a KEYWORD
0 is a NUMBER

BLOCK ENDS
Total number of comments are 3{root@localhost]#