You are on page 1of 19

1.

Write a program to recognize the identifiers in a C program with and without using a
tool.
Algorithm: Recognizing identifier using Flex tool
Step 1: Declare pattern class for digits and letters
Step 2: If input is a keyword, then not a valid identifier
Step 3: If input starts with a alphabet or underscore and contains only alphabet, digit and
underscore then valid identifier
Algorithm: Recognizing identifier without using a tool (using Python)
Step 1: import the regular expression library of python i.e. re
Step 2: Input a string
Step 3: Compile the required regular expression: r'[a-zA-z_][a-zA-Z_0-9]*' in raw string
format
Step 4: Match the input string against the compiled expression.
Step 5: If matched print the pattern otherwise display error message.
Recognize identifier using Flex tool: -
%{
%}
delim [ \t\n\v,]
letter [a-z|A-Z|_]
digit [0-9]
%%
auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|
register|return|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatil
e|while {printf("%s is keyword",yytext);}
{letter}({letter}|{digit})* {printf("%s is valid identifier\n", yytext);}
{digit}+ {printf("%s is valid unsigned integer\n", yytext);}
.* {printf("%s is not a identifier or a valid number\n", yytext);}
%%
int main(void)
{
yylex();
return 0;
}
int yywrap(void)
{
return 1;
}
Sample Output: -
Recognizing identifier without using a tool: -
import re
another=1
while(another==1):
x=input('enter a identifier: ')
pattern=re.compile(r'[a-zA-z_][a-zA-Z_0-9]*')
match=pattern.match(x)
if(match):
print(match.group(0),'is a valid identifier')
else:
print(x,'is not a valid identifier')
another=(int)(input('Another input? 1 for yes/ 0 for no: '))
Sample Output: -
2. Write a program to recognize integers and float numbers in a C program with and
without using a tool.
Algorithm: Recognizing numbers using Flex tool
Step 1: Declare pattern class for digits, exponent (e or E) and sign (+ or -)
Step 2: Regular Expression: - {sign}?{digit}+
{sign}?{digit}+\.{digit}*
{sign}?{digit}+\.?{digit}+{expo}{sign}?{digit}+
Algorithm: Recognizing number without using a tool (using Python)
Step 1: import the regular expression library of python i.e. re
Step 2: Input a string
Step 3: Compile the required regular expression: r'[0-9]+\.?[0-9]*[eE]?[+-]?[0-9]+' in raw
string format
Step 4: Match the input string against the compiled expression.
Step 5: If matched print the pattern otherwise display error message.
Recognizing numbers using Flex tool
%{
%}
digit [0-9]
expo [eE]
sign [-\+]
%%
{sign}?{digit}+ {printf("%s is an integer\n", yytext);}
{sign}?{digit}+\.{digit}* {printf("%s is a real number\n", yytext);}
{sign}?{digit}+\.?{digit}+{expo}{sign}?{digit}+
printf("%s is a real number in scientific notation",yytext);}
.* {printf("%s is invalid\n", yytext);}
%%
int main(void)
{
yylex();
return 0;
}
int yywrap(void)
{
return 1;
}
Sample Output:
Recognizing number without using a tool (using Python)
import re
another=1
while(another==1):
x=input('enter a number: ')
pattern=re.compile(r'[0-9]+\.?[0-9]*[eE]?[+-]?[0-9]+')
match=pattern.match(x)
if(match):
print(match.group(0),'is a valid number')
else:
print(x,'is not a valid number')
another=(int)(input('Another input? 1 for yes/ 0 for no: '))
Sample output: -
3. Write a program to recognize the operators in a C program with and without using a tool.
Algorithm: Recognizing operators using Flex tool
Step 1: Declare pattern class type for type casting data types.
Step 2: Regular Expression for all the types of operators in C program
Algorithm: Recognizing operators without using a tool (using Python)
Step 1: import the regular expression library of python i.e. re
Step 2: Input a string
Step 3: Compile the required regular expression:
r'\+[\+=]?|\-[\-=]?|\*=?|\/=?|%=?|<<?=?|>>?=?|&[&=]?|\|[\|=]?|\!=?|==?|\^=?|~|\?:|"sizeof"'
in raw string format
Step 4: Match the input string against the compiled expression.
Step 5: If matched print the pattern otherwise display error message.
Recognizing operators using Flex tool
%{
%}
type int|float|double|short|long|char|unsigned
%%
\(\) printf("%s is parenthesis operator", yytext);
\[\] printf("%s is array subscript operator",yytext);
\. printf("%s is dot operator",yytext);
-> printf("%s is member selection operator",yytext);
\+\+|-- printf("%s is increment/decrement operator",yytext);
\+|- printf("%s is unary or arithmetic operator",yytext);
\({type}\) printf("%s is cast operator",yytext);
\* printf("%s is dereference or arithmetic operator",yytext);
\& printf("%s is address or bitwise AND operator",yytext);
sizeof printf("%s is sizeof operator",yytext);
\+=|-=|\*=|\/=|%=|&=|^= printf("%s is compound assignment operator",yytext);
= printf("%s is assignment operator",yytext);
\+|-|\*|\/ printf("%s is arithmetic operator",yytext);
&&|\|\||! printf("%s is logical operator",yytext);
\^|\||&|!~ printf("%s is bitwise operator",yytext);
\<<|>> printf("%s is shift operator",yytext);
>=?|<=?|!=|== printf("%s is relational operator",yytext);
\?: printf("%s is conditional operator",yytext);
\, printf("%s is comma operator",yytext);
.* printf("%s is invalid symbol",yytext);
%%
int yywrap(void)
{
return 1;
} Sample Output: -
int main(void)
{
yylex();
return 0;
}
Recognizing operators without using a tool (using Python)
import re
another=1
while(another==1):
x=input('enter a operator: ')
data=re.compile(r'int|char|double|float|short|long|unsigned')
pattern=re.compile(r'\+[\+=]?|\-[\-
=]?|\*=?|\/=?|%=?|<<?=?|>>?=?|&[&=]?|\|[\|=]?|\!=?|==?|\^=?|~|\?:|"sizeof"')
match=pattern.match(x)
if(match):
print(match.group(0),'is a valid operator')
else:
print(x,'is not a valid operator')
another=(int)(input('Another input? 1 for yes/ 0 for no: '))
Sample Output: -
4. Write a program to recognize the keywords in a C program with and without using a tool.
Algorithm: Recognizing keyword using Flex tool
Step 1: Explicitly write all the keywords separated by |
Step 2: Match against given input
Algorithm: Recognizing keyword without using a tool (using Python)
Step 1: import the regular expression library of python i.e. re
Step 2: Input a string
Step 3: Compile the required regular expression:
r'auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|lon
g|register|return|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|vola
tile|while’
in raw string format
Step 4: Match the input string against the compiled expression.
Step 5: If matched print the pattern otherwise display error message.
Recognizing keyword using Flex tool
%{
%}
%%
auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int
|long|register|return|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|vo
id|volatile|while {printf("%s is keyword",yytext);}
.* {printf("%s is not a keyword\n", yytext);}
%%
int main(void)
{
yylex();
return 0;
}
int yywrap(void)
{
return 1;
}
Sample Output: -
Recognizing keyword without using a tool (using Python)
import re
another=1
while(another==1):
x=input('enter a string: ')
key=re.compile(r'auto|break|case|char|const|continue|default|do|double|else|enum|ext
ern|float|for|goto|if|int|long|register|return|return|short|signed|sizeof|static|struct|sw
itch|typedef|union|unsigned|void|volatile|while')
match=key.match(x)
if(match):
print(match.group(0),'is a keyword')
else:
print(x,'is not a keyword')
another=(int)(input('Another input? 1 for yes/ 0 for no: '))
Sample Output: -
5. Write a C program to implement symbol table.
Algorithm:
Step 1: A hash table of size 100 which contains pointer to their corresponding head of linked list is
initialized with NULL value.
Step 2: index=ascii_sum(input)%100 is the hash function
Step 3: if head[index] is NULL, then create a node and link it to the head[index]
Step 4: if head[index] is not NULL then the input has been already inserted into the symbol table
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 80
int asciiSum(char id[])
{
int i=0,sum=0;
if(strlen(id)>3)
return -1;
while(i<strlen(id))
{
sum=sum+id[i];
i++;
}
return sum;
}
struct node
{
char tname[MAX];
int id;
struct node *next;
};
struct node *head[100];
void init()
{
int i;
for(i=0;i<100;i++)
head[i]=NULL;
}
int insert(char name[])
{
int s=asciiSum(name);
int index=-1,flag=0;
struct node *newnode;
if(s<=-1)
{
printf("identifier of size less than 4 is required");
return 0;
}
index=s%100;
if(head[index]==NULL)
{
newnode=(struct node *)malloc(sizeof(struct node));
// newnode->tname=name;
newnode->id=index;
newnode->next=NULL;
head[index]=newnode;
flag=-1;
}
else
{
flag=(int)(head[index]);
}
return flag;
}
int main(void)
{
char id[MAX];
int another=0;
int result=0;
init();
do
{
printf("Enter an identifier of three characters: ");
scanf("%s",id);
result=insert(id);
if(result==-1)
printf("Insertion successfull\n");
else
printf("%s already exist. id= %d\n", id,result);
printf(("Another identifier? 1 for yes/ 0 for no\n"));
scanf("%d",&another);
}while(another==1);
}
Sample Output: -
6. Implement the Lexical Analyzer; (a) using C language and (b) using a tool.
Lexical Analyzer using C
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Returns 'true' if the character is a DELIMITER.
bool isDelimiter(char ch)
{
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == ',' || ch == ';' || ch == '>' ||
ch == '<' || ch == '=' || ch == '(' || ch == ')' ||
ch == '[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false);
}
// Returns 'true' if the character is an OPERATOR.
bool isOperator(char ch)
{
if (ch == '+' || ch == '-' || ch == '*' ||
ch == '/' || ch == '>' || ch == '<' ||
ch == '=')
return (true);
return (false);
}
// Returns 'true' if the string is a VALID IDENTIFIER.
bool validIdentifier(char* str)
{
if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||
str[0] == '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||
str[0] == '9' || isDelimiter(str[0]) == true)
return (false);
return (true);
}
// Returns 'true' if the string is a KEYWORD.
bool isKeyword(char* str)
{
if (!strcmp(str, "if") || !strcmp(str, "else") ||
!strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") ||
!strcmp(str, "continue") || !strcmp(str, "int")
|| !strcmp(str, "double") || !strcmp(str, "float")
|| !strcmp(str, "return") || !strcmp(str, "char")
|| !strcmp(str, "case") || !strcmp(str, "char")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str, "typedef")
|| !strcmp(str, "switch") || !strcmp(str, "unsigned")
|| !strcmp(str, "void") || !strcmp(str, "static")
|| !strcmp(str, "struct") || !strcmp(str, "goto"))
return (true);
return (false);
}
// Returns 'true' if the string is an INTEGER.
bool isInteger(char* str)
{
int i, len = strlen(str);
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}
// Returns 'true' if the string is a REAL NUMBER.
bool isRealNumber(char* str)
{
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
// Extracts the SUBSTRING.
char* subString(char* str, int left, int right)
{
int i;
char* subStr = (char*)malloc(
sizeof(char) * (right - left + 2));
for (i = left; i <= right; i++)
subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr);
}
// Parsing the input STRING.
void parse(char* str)
{
int left = 0, right = 0;
int len = strlen(str);
while (right <= len && left <= right) {
if (isDelimiter(str[right]) == false)
right++;
if (isDelimiter(str[right]) == true && left == right) {
if (isOperator(str[right]) == true)
printf("'%c' IS AN OPERATOR\n", str[right]);
right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
if (isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr);
else if (isInteger(subStr) == true)
printf("'%s' IS AN INTEGER\n", subStr);
else if (isRealNumber(subStr) == true)
printf("'%s' IS A REAL NUMBER\n", subStr);
else if (validIdentifier(subStr) == true
&& isDelimiter(str[right - 1]) == false)
printf("'%s' IS A VALID IDENTIFIER\n", subStr);
else if (validIdentifier(subStr) == false
&& isDelimiter(str[right - 1]) == false)
printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr);
left = right;
}
}
return;
}
// DRIVER FUNCTION
int main()
{
// maximum legth of string is 100 here
char str[100] = "int a = b + 1c; ";
printf("Enter a program line: ");
scanf("%[^'\n']s",str);
parse(str); // calling the parse function
system("pause");
return (0);
}
Sample Output: -
Lexical Analyzer using Flex tool
%{
%}
type int|float|double|short|long|char|unsigned
letter [a-z|A-Z|_]
digit [0-9]
sign [\+-]
expo [eE]
delim [ \t\n]
end ;
%%
auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|
return|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while
{printf("%s is keyword\n",yytext);}
sizeof printf("%s is sizeof operator\n",yytext);
{letter}+{digit}* {printf("%s is valid identifier\n", yytext);}
{digit}+ {printf("%s is valid unsigned integer\n", yytext);}
{sign}?{digit}+ {printf("%s is an integer\n", yytext);}
{sign}?{digit}+\.{digit}* {printf("%s is a real number\n", yytext);}
{sign}?{digit}+\.?{digit}+{expo}{sign}?{digit}+
{printf("%s is a real number in scientific notation\n",yytext);}
\(\) printf("%s is parenthesis operator\n", yytext);
\[\] printf("%s is array subscript operator\n",yytext);
\. printf("%s is dot operator\n",yytext);
-> printf("%s is member selection operator\n",yytext);
\+\+|-- printf("%s is increment/decrement operator\n",yytext);
\+|- printf("%s is unary or arithmetic operator\n",yytext);
\({type}\) printf("%s is cast operator\n",yytext);
\* printf("%s is dereference or arithmetic operator\n",yytext);
\& printf("%s is address or bitwise AND operator\n",yytext);
\+=|-=|\*=|\/=|%=|&=|^= printf("%s is compound assignment operator\n",yytext);
= printf("%s is assignment operator\n",yytext);
\+|-|\*|\/ printf("%s is arithmetic operator\n",yytext);
&&|\|\||! printf("%s is logical operator\n",yytext);
\^|\||&|!~ printf("%s is bitwise operator\n",yytext);
\<<|>> printf("%s is shift operator\n",yytext);
>=?|<=?|!=|== printf("%s is relational operator\n",yytext);
\?: printf("%s is conditional operator\n",yytext);
\, printf("%s is comma operator\n",yytext);
{delim} {}
{end} printf("%s is end of statement\n",yytext);
. {printf("%s is not a keyword\n", yytext);}
%%
int main(void)
{ Sample Output: -
yylex();
return 0;
}
int yywrap(void)
{
return 1;
}
7. Write a program to parse a given string with recursive descent parser using tool(s).
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
char next;
void E(void);
void T(void);
void S(void);
void F(void);
void error(int);
void scan(void);
int main() {
scan();
E();
if (next != '$') error(1);
else printf("Success\n");
}
void E(void) {
T();
while (next == '+' || next == '-') {
scan();
T();
}
}
void T(void) {
S();
while (next == '*' || next == '/') {
scan();
S();
}
}
void S(void) {
F();
if (next == '^') {
scan();
S();
}
}
void F(void) {
if (isalpha(next)) {
scan();
}
else if (next == '(') {
scan();
E();
if (next == ')') scan();
else error(2);
}
else {
error(3);
}
}
void scan(void) {
while (isspace(next = getchar()))
;
}
void error(int n) {
printf("\n*** ERROR: %i\n", n);
exit(1);
}
Sample Output:-
8. Write a program to generate the parse table for given grammar.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char fin[10][20],st[10][20],ft[20][20],fol[20][20];
int a=0,e,i,t,b,c,n,k,l=0,j,s,m,p;
clrscr();
printf("enter the no. of coordinates\n");
scanf("%d",&n);
printf("enter the productions in a grammar\n");
for(i=0;i<n;i++)
scanf("%s",st[i]);
for(i=0;i<n;i++)
fol[i][0]='\0';
for(s=0;s<n;s++)
{
for(i=0;i<n;i++)
{
j=3;
l=0;
a=0;
l1:if(!((st[i][j]>64)&&(st[i][j]<91)))
{
for(m=0;m<l;m++)
{
if(ft[i][m]==st[i][j])
goto s1;
}
ft[i][l]=st[i][j];
l=l+1;
s1:j=j+1;
}
else
{
if(s>0)
{
while(st[i][j]!=st[a][0])
{
a++;
}
b=0;
while(ft[a][b]!='\0')
{
for(m=0;m<l;m++)
{
if(ft[i][m]==ft[a][b])
goto s2;
}
ft[i][l]=ft[a][b];
l=l+1;
s2:b=b+1;
}
}
}
while(st[i][j]!='\0')
{
if(st[i][j]=='|')
{
j=j+1;
goto l1;
}
j=j+1;
}
ft[i][l]='\0';
}
}
printf("first pos\n");
for(i=0;i<n;i++)
printf("FIRS[%c]=%s\n",st[i][0],ft[i]);
fol[0][0]='$';
for(i=0;i<n;i++)
{
k=0;
j=3;
if(i==0)
l=1;
else
l=0;
k1:while((st[i][0]!=st[k][j])&&(k<n))
{
if(st[k][j]=='\0')
{
k++;
j=2;
}
j++;
}
j=j+1;
if(st[i][0]==st[k][j-1])
{
if((st[k][j]!='|')&&(st[k][j]!='\0'))
{
a=0;
if(!((st[k][j]>64)&&(st[k][j]<91)))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==st[k][j])
goto q3;
}
fol[i][l]=st[k][j];
l++;
q3:
}
else
{
while(st[k][j]!=st[a][0])
{
a++;
}
p=0;
while(ft[a][p]!='\0')
{
if(ft[a][p]!='@')
{
for(m=0;m<l;m++)
{
if(fol[i][m]==ft[a][p])
goto q2;
}
fol[i][l]=ft[a][p];
l=l+1;
}
else
e=1;
q2:p++;
}
if(e==1)
{
e=0;
goto a1;
}
}
}
else
{
a1:c=0;
a=0;
while(st[k][0]!=st[a][0])
{
a++;
}
while((fol[a][c]!='\0')&&(st[a][0]!=st[i][0]))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==fol[a][c])
goto q1;
}
fol[i][l]=fol[a][c];
l++;
q1:c++;
}
}
goto k1;
}
fol[i][l]='\0';
}
printf("follow pos\n");
for(i=0;i<n;i++)
printf("FOLLOW[%c]=%s\n",st[i][0],fol[i]);
printf("\n");
s=0;
for(i=0;i<n;i++)
{
j=3;
while(st[i][j]!='\0')
{
if((st[i][j-1]=='|')||(j==3))
{
for(p=0;p<=2;p++)
{
fin[s][p]=st[i][p];
}
t=j;
for(p=3;((st[i][j]!='|')&&(st[i][j]!='\0'));p++)
{
fin[s][p]=st[i][j];
j++;
}
fin[s][p]='\0';
if(st[i][k]=='@')
{
b=0;
a=0;
while(st[a][0]!=st[i][0])
{
a++;
}
while(fol[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],fol[a][b],fin[s]);
b++;
}
}
else if(!((st[i][t]>64)&&(st[i][t]<91)))
printf("M[%c,%c]=%s\n",st[i][0],st[i][t],fin[s]);
else
{
b=0;
a=0;
while(st[a][0]!=st[i][3])
{
a++;
}
while(ft[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],ft[a][b],fin[s]);
b++;
}
}
s++;
}
if(st[i][j]=='|')
j++;
}
}
getch();
}
OutPut:
Enter the no. of co-ordinates
2
Enter the productions in a grammar
S->CC
C->eC | d
First pos
FIRS[S] = ed
FIRS[C] = ed
Follow pos
FOLLOW[S] =$
FOLLOW[C] =ed$
M [S , e] =S->CC
M [S , d] =S->CC
M [C , e] =C->eC
M [C , d] =C->d
9. Write a program to parse a given string with recursive predictive parser using tool(s).
//To Implement Predictive Parsing
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char a[10];
int top=-1,i;
void error(){
printf("Syntax Error");
}
void push(char k[]) //Pushes The Set Of Characters on to the Stack
{
for(i=0;k[i]!='\0';i++)
{
if(top<9)
a[++top]=k[i];
}
}
char TOS() //Returns TOP of the Stack
{
return a[top];
}
void pop() //Pops 1 element from the Stack
{
if(top>=0)
a[top--]='\0';
}
void display() //Displays Elements Of Stack
{
for(i=0;i<=top;i++)
printf("%c",a[i]);
}
void display1(char p[],int m) //Displays The Present Input String
{
int l;
printf("\t");
for(l=m;p[l]!='\0';l++)
printf("%c",p[l]);
}
char* stack(){
return a;
}
int main()
{
char ip[20],r[20],st,an;
int ir,ic,j=0,k;
char t[5][6][10]={"$","$","TH","$","TH","$",
"+TH","$","e","e","$","e",
"$","$","FU","$","FU","$",
"e","*FU","e","e","$","e",
"$","$","(E)","$","i","$"};
system("cls");
printf("\nEnter any String(Append with $)");
gets(ip);
printf("Stack\tInput\tOutput\n\n");
push("$E");
display();
printf("\t%s\n",ip);
for(j=0;ip[j]!='\0';)
{
if(TOS()==an)
{
pop();
display();
display1(ip,j+1);
printf("\tPOP\n");
j++;
}
an=ip[j];
st=TOS();
if(st=='E')ir=0;
else if(st=='H')ir=1;
else if(st=='T')ir=2;
else if(st=='U')ir=3;
else if(st=='F')ir=4;
else {
error();
break;
}
if(an=='+')ic=0;
else if(an=='*')ic=1;
else if(an=='(')ic=2;
else if(an==')')ic=3;
else if((an>='a'&&an<='z')||(an>='A'&&an<='Z')){ic=4;an='i';}
else if(an=='$')ic=5;
strcpy(r,strrev(t[ir][ic]));
strrev(t[ir][ic]);
pop();
push(r);
if(TOS()=='e')
{
pop();
display();
display1(ip,j);
printf("\t%c->%c\n",st,238);
}
else{
display();
display1(ip,j);
printf("\t%c->%s\n",st,t[ir][ic]);
}
if(TOS()=='$'&&an=='$')
break;
if(TOS()=='$'){
error();
break;
}
}
k=strcmp(stack(),"$");
if(k==0)
printf("\n Given String is accepted");
else
printf("\n Given String is not accepted");
return 0;
}
Sample Output:-
10. Write a program for a desk calculator using tool(s).
Simple Desk Calculator using Flex and Bison Tool
The lex file: calc.l
%{
#include <stdlib.h>
void yyerror(char *);
#include "calc.tab.h"
%}
%%
[0-9]+ {yylval = atoi(yytext);return INTEGER;}
[-+*/\n] return *yytext;
[ \t] ; /* skip whitespace */
. yyerror("invalid character");
%%
int yywrap(void) {
return 1;
}
The yacc file: calc.y
%{
#include <stdio.h>
int yylex(void);
void yyerror(char *);
%}
%token INTEGER
%%
program:
program expr '\n' { printf("%d\n", $2); }
|
;
expr:
INTEGER { $$ = $1; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
;
%%
void yyerror(char *s)
{
fprintf(stderr, "%s\n", s);
}
int main(void)
{
yyparse();
return 0;
}
Sample Output: -

You might also like