Sie sind auf Seite 1von 25

SS & CD Lab

1

VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELGAUM - 590014

1 VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELGAUM - 590014 VI Sem CSE SS & CD LAB MANUAL Prepared
VI Sem CSE
VI Sem
CSE

SS & CD LAB MANUAL

Prepared by Mrs. RASAGNA REDDY Lecturer

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

K.N.S INSTITUTE OF TECHNOLOGY, BANGALORE -560045

2011-12

SS & CD Lab

2

PART – A

LEX AND YACC PROGRAMS:

Execute the following programs using LEX:

Program 1a Program to count the number of characters, words, spaces and lines in a given input file. %{ /*This is definition sec*/ int cc=0,wc=0,sc=0,lc=0;

%} /*This is rules sec*/ %% [ ] {sc++;cc++;} [^ \t\n]+ {wc++;cc+=yyleng;} [\n] {lc++;cc++;} [\t] {sc+=8;cc++;} %%

/*This is user defined subroutine section*/ int main()

{

char fname[20]; printf(“Enter a file name:\n”); scanf(“%s”,fname); yyin=fopen(fname,"r"); yylex(); fclose(yyin);

yyin=fopen(fname,"r"); yylex(); fclose(yyin); printf("The no.of characters = %d\n",cc);

printf("The no.of characters = %d\n",cc); printf("The no.of spaces = %d\n",sc); printf("The no.of lines = %d\n",lc); printf("The no.of words = %d\n",wc);

}

Output:-

[student@localhost ~]# vi ex Note: A file will be opened enter some lines of sentences in it. Come back by typing

Esc :wq [student@localhost ~]# lex 1a.l [student@localhost ~]# cc lex.yy.c -ll [student@localhost usp]# ./a.out Enter a file name:

ex The no.of characters = 40 The no.of spaces = 5 The no.of lines = 3 The no.of words = 7

SS & CD Lab

3

Program 1b Program to count the numbers of comments lines in a given C program. Also eliminate them and copy the resulting program into separate file.

%{ int comment=0; %}

%% “//”.* {comment++; fprintf(yyout,” ”);} ^[ \t]*”/*”.* {BEGIN COMMENT; fprintf(yyout,” ”);} ^[ \t]*”/*”.*”*/”[ \t]*\n {comment++;fprintf(yyout,” ”);} <COMMENT>.*”*/”*[ \t]*\n {BEGIN 0;comment++;fprintf(yyout,” ”);} <COMMENT>”*/” {BEGIN 0;fprintf(yyout,” ”);} <COMMENT>\n {comment++;fprintf(yyout,” ”);} <COMMENT>.*\n {comment++;fprintf(yyout,” ”);} . {fprintf(yyout,yytext);} %%

int main()

{

”);} . {fprintf(yyout,yytext);} %% int main() { yyin=fopen("ex","r");

yyin=fopen("ex","r"); yyout=fopen("result","w"); yylex(); fclose(yyin); fclose(yyout); system("cat result"); printf("\n\nThe no.of comment lines = %d",comment); return 0;

}

Output:-

[student@localhost usp]# vi ex [Note: Enter some content into this file]

//This is single line comment This is not a comment line /* This is a single line comment */ Next line is a multi line comment /* This is multi line comment */

[student@localhost usp]# lex 1b.l [student@localhost usp]# cc lex.yy.c -ll [student@localhost usp]# ./a.out

SS & CD Lab

4

This is not a comment line Next line is a multi line comment

The no.of comment lines = 5

Program 2a Program to recognize a valid arithmetic expression and to recognize the identifiers and operators present. Print them separately.

%{ int opdcount=0,oprcount=0,i=0,j=0,k=0; char opd[20],opr[20]; %} OPERATOR [+\-\*\/] OPERANDS [a-zA-Z0-9]+ %%
%{
int opdcount=0,oprcount=0,i=0,j=0,k=0;
char opd[20],opr[20];
%}
OPERATOR [+\-\*\/]
OPERANDS [a-zA-Z0-9]+
%%
{OPERATOR} {oprcount++;opr[i++]=yytext[0];opr[i++]=’ ‘;}
{OPERANDS} {opdcount++;for(j=0;j<yyleng;j++) opd[k++]=yytext[j];
opd[k++]=’ ‘;}
. {}
%%
int main()
{
yylex();
if((opdcount-oprcount)!=1)
printf(“Not valid expression\n”);
else
{
printf(“Valid\n”);
printf(“the operands = %s and count = %d\n”,opd,opdcount);
printf(“The operators = %s and count = %d\n”,opr,oprcount);
}
return 1;
}
Output:-

[student@localhost ~]# lex 2a.l [student@localhost ~]# cc lex.yy.c -ll [student@localhost ~]# ./a.out a+b Valid The operands = a b and count = 2

SS & CD Lab

5

The operators = + and count=1

[student@localhost ~]# ./a.out a+b*(e*d)/f*(h-g) Valid The operands = a b e d f h g and count = 7 The operators = + * * / * - and count=6

Program 2b Program to recognize whether a given sentence is simple or compound.

printf("Compound sentence\n"); printf("Simple sentence\n"); return 0;
printf("Compound sentence\n");
printf("Simple sentence\n");
return 0;

int flag=0;

Printf(“Enter a sentence:\n”); yylex();

if(flag==1)

else

%{

%}

int main()

{

}

Output:-

[student@localhost ~]# vi 2b.l [student@localhost ~]# lex 2b.l [student@localhost ~]# cc lex.yy.c -ll [student@localhost ~]# ./a.out This is usp lab

%% (" "[aA][nN][dD]" "|" "[oO][rR]" "|" "[bB][uU][tT]" "|" " [eE][iI][tT][hH][eE][rR] " "|" "[nN][eE][iI][tT][hH][eE][rR] " "|" "[nN][oO][rR]" "|" "[bB][eE][cC][aA][uU][sS][eE] " ") {flag=1;} ; %%

.

Simple sentence [student@localhost ~]# ./a.out recognize and count the number of identifiers

Compound sentence [student@localhost ~]# ./a.out

SS & CD Lab

6

recognize but not identified

Compound sentence [student@localhost usp]# ./a.out recognize or count

Compound sentence [student@localhost usp]# ./a.out recognize But not count

Compound sentence %{ int count=0; %} SPLCH [!@#$%^&] DIGIT [0-9] LETTER [a-zA-Z] USCORE "_" %%
Compound sentence
%{
int count=0;
%}
SPLCH [!@#$%^&]
DIGIT [0-9]
LETTER [a-zA-Z]
USCORE "_"
%%
%%
int main()
{
yyin=fopen("ex","r");
system(“cat ex”);
yylex();
fclose(yyin);
printf("no of identifiers = %d",count);
return 1;
}
Output:-

Program 3 program to recognize and count the number of identifiers in a given input file.

(({LETTER}|{USCORE})+({LETTER}{DIGIT}|{USCORE})*) {count++;} . {} (({LETTER}|{DIGIT}|{USCORE}|{SPLCH})+({LETTER}|{DIGIT}|{USCORE}|{SPLCH})*) {}

[student@localhost ~]# lex 3.l [student@localhost ~]# cc lex.yy.c -ll [student@localhost ~]# ./a.out

1243_4664

SS & CD Lab

7

filename

a

_sdsds

no

data

no. of identifiers = 5

Execute the following programs using YACC: Program 4a Program to recognize a valid arithmetic expression
Execute the following programs using YACC:
Program 4a
Program to recognize a valid arithmetic expression that uses operators
+, -, *, and /.
%{
#include<stdio.h>
#include<ctype.h>
%}
%token digit letter
%left '+' '-'
%right UMINUS
%left '*' '/'
%%
lines:
|lines exp '\n' {printf(“valid\n”);}
|lines '\n'
;
exp:exp'+'exp
|exp'-'exp
|exp'*'exp
|exp'/'exp
|'('exp')'
|'-'exp
|letter

|number

;

number: number digit | digit

;

%%

int yylex()

{

SS & CD Lab

8

int c; while((c=getchar())==' '); if(isalpha(c)) return letter; if(isdigit(c)) return digit; return c;

} int main() { yyparse(); return 0; } int yyerror() { printf("Error\n"); return 0; }
}
int main()
{
yyparse();
return 0;
}
int yyerror()
{
printf("Error\n");
return 0;
}
Output:-
[student@localhost ~]# yacc 4a.y
[student@localhost ~]# cc y.tab.c
[student@localhost ~]# ./a.out
a+b*c
Valid
a*d+(a-b)*c
Valid
(a*c)*(d+4)
Valid
-b*
Invalid
%{
#include<stdio.h>
#include<ctype.h>
%}

Program 4b Program to recognize a valid variable, which starts with a letter, followed by any number of letters or digits.

%token letter digit

%% id:id letter '\n' {printf("Valid\n");} |id letter other '\n' {printf("Valid\n");}

SS & CD Lab

9

|

;

other:other letter |other digit |letter |digit

;

%%

yyparse(); return 0; printf("Error\n"); return 0; int c; while((c=getchar())==' '); if(isalpha(c))
yyparse();
return 0;
printf("Error\n");
return 0;
int c;
while((c=getchar())==' ');
if(isalpha(c)) return letter;
if(isdigit(c)) return digit;
else return c;

int main()

{

}

int yyerror()

{

}

int yylex()

{

}

Output:-

[student@localhost ~]# yacc 4b.y [student@localhost ~]# cc y.tab.c -ly [student@localhost ~]# ./a.out

a2772

Valid

affff

Valid

name

Valid

67676

Error

SS & CD Lab

10

Program 5a Program to evaluate an arithmetic expression involving operators +, -, *, and /.

%{

#include<stdio.h> #include<ctype.h> #define YYSTYPE double %} %token num %left '+'
#include<stdio.h>
#include<ctype.h>
#define YYSTYPE double
%}
%token num
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
lines:
|lines exp '\n' {printf("%g\n",$2); return 1;}
|lines '\n'
;
exp:exp'+'exp {$$=$1+$3;}
|exp'-'exp {$$=$1-$3;}
|exp'*'exp {$$=$1*$3;}
|exp'/'exp {if($3==0)
{
printf("Divide by zero error\n");
exit(0);
}
$$=$1/$3;
}
|'('exp')' {$$=$2;}
|'-'exp {$$=-$2;}
|num
;
%%

int yylex()

{

int c;

while((c=getchar())==' '); if((c=='.')||(isdigit(c)))

{

ungetc(c,stdin); scanf("%lf",&yylval); return num;

SS & CD Lab

11

}

return c;

}

int main()

{

yyparse();

return 0; } int yyerror() { printf("Error\n"); return 0; } Output:- [student@localhost ~]# yacc 5a.y
return 0;
}
int yyerror()
{
printf("Error\n");
return 0;
}
Output:-
[student@localhost ~]# yacc 5a.y
[student@localhost ~]# cc y.tab.c
[student@localhost ~]# ./a.out
4+4
8
[student@localhost ~]# ./a.out
12+3*(23-5)
66
[student@localhost ~]# ./a.out
-55+(5*5)
-30
Program 5b
Program
to
recognize
strings
'aaab',
'abbb',
'ab',
and
'a'
using
grammar (a n b n ,n>=0).
%{
#include<stdio.h>
#include<ctype.h>
%}

%token ta tb

%%

S: T ‘\n’ {printf("Valid\n"); exit(0);}

;

T:

|ta T tb

;

the

SS & CD Lab

12

%%

int yylex()

{

int c; while((c=getchar())==' '); if(c=='a') return ta; if(c=='b') return tb; return c;

} int main() { yyparse(); return 0; } int yyerror() { printf("Error\n"); return 0; }
}
int main()
{
yyparse();
return 0;
}
int yyerror()
{
printf("Error\n");
return 0;
}
Output:-
[student@localhost ~]# vi 5b.y
[student@localhost ~]# yacc 5b.y
[student@localhost ~]# cc y.tab.c
[student@localhost ~]# ./a.out
aaab
In valid
[student@localhost ~]# ./a.out
aaaaabbbbb
Valid
ab
Valid
[student@localhost ~]# ./a.out

abbb

In valid

[student@localhost ~]# ./a.out

a

Error

[student@localhost ~]# ./a.out

Valid

[no input entered]

SS & CD Lab

13

Program 6 Program to recognize the grammar (a n b ,n>=10).

%{

 

#include<stdio.h>

#include<ctype.h>

%}

%token ta tb

%% v: |v ta ta ta ta ta ta ta ta ta ta p '\n'
%%
v:
|v ta ta ta ta ta ta ta ta ta ta p '\n' {printf("Valid\n");}
;
p:ta p
|tb
;
%%
int yylex()
{
int c;
while((c=getchar())==' ');
if(c=='a') return ta;
if(c=='b') return tb;
return c;
}
int main()
{
yyparse();
return 0;
}
int yyerror()
{
printf("Error\n");
return 0;
}
Output:-

[student@localhost ~]# yacc 6.y [student@localhost ~]# cc y.tab.c

[student@localhost ~]# ./a.out aab

SS & CD Lab

14

Error [student@localhost ~]# ./a.out aaaaaaaaaab Valid aaaaaaaaaaaaaaaab Valid aaaaaaaaaabbbbbb Error

PART – B
PART – B

UNIX PROGRAMMING:

Program 1a Non-recursive shell script that accepts any number of arguments and prints them in the Reverse order, ( For example, if the script is named rargs, then executing rargs A B C should produce C B A on the standard output).

if [ $# -eq 0 ] then echo "NO ARGUMENTS" else while [ $# -ne 0 ] do x=$1" "$x shift done echo "THE REVERSED STRING IS :$x" fi

Output:

[student@localhost ~]$ sh vijet NO ARGUMENTS [student@localhost ~]$ sh vijet d o g THE REVERSED STRING IS :g o d

Program 1b C program that creates a child process to read commands from the standard input and execute them ( a minimal implementation of a shell – like program). You can assume that no arguments will be passed to the commands to be executed. #include<stdio.h> #include<sys/types.h> #include<unistd.h> #include<fcntl.h>

SS & CD Lab

15

int main()

{

int s;

char c[20];

pid_t pid;

pid=fork();

if(pid==0)

{

printf("enter the valid unix command\n"); scanf("%s",c); system(c); } pid=waitpid(pid,&s,0);
printf("enter the valid unix command\n");
scanf("%s",c);
system(c);
}
pid=waitpid(pid,&s,0);
return 0;
}
Output:
[student@localhost ~]$ vi mann.c
[student@localhost ~]$ cc mann.c
[student@localhost ~]$ ./a.out
enter the valid unix command
cal
May 2012
Su Mo Tu We Th Fr Sa
1
2
3
4
5
6
7 8
9 10 11 12
13
14 15 16 17 18 19
20
21 22 23 24 25 26
27
28 29 30 31
[student@localhost ~]$ ./a.out
enter the valid unix command
date
Tue May 15 15:22:13 EDT 2012
[student@localhost ~]$ ./a.out
enter the valid unix command
ls
; 3.c 4b.c 6.y a.c arp.l cht.l
first.c kantharaj loka.c man.l op
pro.c1 second.c veer1.sh viju1

[student@localhost ~]$ ./a.out enter the valid unix command pwd /home/student

SS & CD Lab

16

Program 2a Shell script that accepts two files names as arguments, checks if the permissions for these files are identical and if the permissions are identical, outputs the common permissions, otherwise outputs each file name followed by its permissions.

if [ $# -ne 2 ] then echo "no arguments" elif [ ! -e $1 -o ! -e $2 ] then echo "file doesnot exist" else p1=`ls -l $1|cut -c2-10` p2=`ls -l $2|cut -c2-10` if [ $p1 == $p2 ] then echo "file permissions are equal and are $p1" else echo "file permission are not equal" echo "permission of $1 is $p1" echo "permission of $2 is $p2" fi fi

$1 is $p1" echo "permission of $2 is $p2" fi fi Output: [student@localhost ~]$ sh per.sh

Output:

[student@localhost ~]$ sh per.sh no arguments [student@localhost ~]$ sh per.sh 3.c 4.c file permission are not equal permission of 3.c is rwxrwxrwx permission of 4.c is rw-rw-r-- [student@localhost ~]$ sh per.sh a.c 4.c file permissions are equal and are rw-rw-r--

Program 2b C program to create a file with 16 bytes of arbitrary data from the beginning and another 16 bytes of arbitrary data from an offset of 48. Display the file to demonstrate how the hole in file is handled.

#include<unistd.h>

#include<sys/types.h>

#include<stdio.h>

SS & CD Lab

17

#include<fcntl.h>

#include<sys/stat.h> int main()

{

char s[16]="lokeshajaylokaja";

char f[16]="fhfkjfhjhfjhfjhf"; int fd;

fd=creat("la",7);

write(fd,s,16);

lseek(fd,48,SEEK_SET);

write(fd,s,16); lseek(fd,48,SEEK_SET); write(fd,f,16); return 0; } Output: [student@localhost ~]$

write(fd,f,16);

return 0;

}

Output:

[student@localhost ~]$ cc loka.c [student@localhost ~]$ ./a.out loka.c [student@localhost ~]$ ./a.out [student@localhost ~]$ vi la [student@localhost ~]$ vi loka.c

okeshajaylokaja^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@

^@^@^@^@^@^@^@^@^@^@^@^@^@fhfkjfhjhfjhfjhf

Program 3a Shell function that takes a valid directory names as an arguments and recursively descends all the subdirectories, finds the maximum length of any file in that hierarchy and write this maximum value to the standard output.

if [ $# -ne 1 ] then echo "NO ARGUMENTS" exit fi if [ ! -e $1 ] then echo "given directory does not exist" exit fi echo "the file with maximum length $1 directory is" ls -lR $1 | tr -s " " | cut -d " " -f5 | sort -n | tail -n 1

SS & CD Lab

18

output:

[student@localhost ~]$ mkdir kantharaj [student@localhost ~]$ cd kantharaj [student@localhost kantharaj]$ cat > l1 kuhf gfhfg [student@localhost kantharaj]$ cat > l2 sthj jhbi [student@localhost kantharaj]$ cat > l3 jhg8ojhydef lkijdf [student@localhost kantharaj]$ cd [student@localhost ~]$ sh v NO ARGUMENTS [student@localhost ~]$ sh v kantharaj

~]$ sh v NO ARGUMENTS [student@localhost ~]$ sh v kantharaj the file with maximum lengthkantharaj directory

the file with maximum lengthkantharaj directory is

19

Program 3b C program that accepts valid file names as command line arguments and for each of the arguments, prints the type of the file (Regular file, Directory file, Character special file, Block special file, Symbolic link etc.)

#include<stdio.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<unistd.h>

int main(int argc,char **argv)

{

struct stat s; int i;

if(argc==1)

printf("No arguments\n"); else

for(i=1;i<argc;i++)

{

lstat(argv[i],&s); if(S_ISREG(s.st_mode)) printf("%s is a regular file \n",argv[i]); if(S_ISDIR(s.st_mode)) printf("%s is a directory file \n",argv[i]); else if(S_ISCHR(s.st_mode)) printf("%s is a character device file \n",argv[i]); else if(S_ISBLK(s.st_mode)) printf("%s is a block device file\n",argv[i]);

SS & CD Lab

19

else

if(S_ISLNK(s.st_mode)) printf("%s is a symbolic link file \n",argv[i]);

}

return 0;

}

output:

[student@localhost ~]$ ./a.out 3.c 3.c is a regular file [student@localhost ~]$ ./a.out /dev/vcs /dev/vcs is a character device file

~]$ ./a.out /dev/vcs /dev/vcs is a character device file Program 4a Shell script that accepts file

Program 4a Shell script that accepts file names specified as arguments and creates a shell script that contains this file as well as the code to recreate these files. Thus if the script generated by your script is executed, it would recreate the original files.

echo "to unbundle sh this file" for i in $* do if [ ! -f $i ] then echo "$i doesnot exist ">/dev/tty fi echo "echo $i is created" echo "cat>$i<<end" cat $i echo "end" done

output:

[student@localhost ~]$ sh 4a.sh to unbundle sh this file [student@localhost ~]$ cat>f1

sdfqw4e5

[Press Ctrl+D]

[student@localhost ~]$ cat>f2

etr235edrf

[Press Ctrl+D]

[student@localhost ~]$ cat>f3

erre5t45y

[Press Ctrl+D]

[student@localhost ~]$ sh 4a.sh f1 f2 f3> zip

[student@localhost ~]$ mkdir rasagna [student@localhost ~]$ cd rasagna

SS & CD Lab

20

[student@localhost rasagna]$ sh

/zip

/zip:

line 1: to: command not found

f1 is created f2 is created f3 is created

Program 4b

C program to do the following: Using fork() create a child process. The child process prints its own process-id and id of its parent and then exits. The parent process waits for its child to finish(by executing the wait()) and prints its own process-id and the id of its child process and then exits. #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> #include<fcntl.h> int main()

{

pid_t pid;

#include<fcntl.h> int main() { pid_t pid; pid=fork(); if(pid == 0) { printf("IN CHILD

pid=fork(); if(pid == 0)

{

printf("IN CHILD PROCESS\n"); printf("child process id is %d\n",getpid());

printf("parent process id is %d\n",getppid());

_exit(0);

}

pid=waitpid(0);

printf("IN PARENT PROCESS\n"); printf("child process id is %d\n",pid);

printf("parent process id is %d\n",getpid()); return 0;

}

Output:

[student@localhost ~]$ ./a.out IN CHILD PROCESS child process id is 2389 parent process id is 2388 IN PARENT PROCESS child process id is 2389 parent process id is 2388

SS & CD Lab

21

COMPILER DESIGN PROGRAMS:

1. Write a C program to implement the syntax directed definition of

“if E then S1” and “if E then S1 else S2”. [Execute this program in turbo C (file extension as .C) instead of fedora since gets function throws a warning in fedora] #include<stdio.h> #include<stdlib.h> #include<string.h> int parsecondition(char[], int, char*, int); void gen(char [],char [],char [],int); int main()

{ int ct=0,len=0,eflag=0; char stmt[60]; char stB[54],stS1[50],stS2[45]; clrscr(); printf("Format of if
{
int ct=0,len=0,eflag=0;
char stmt[60];
char stB[54],stS1[50],stS2[45];
clrscr();
printf("Format of if statement\nExample:\n");
printf("if (a<b) then (s=a);\n");
printf("if (a>b) then (s=a) else (s=b);\n");
printf("Enter the statement\n");
gets(stmt);
len=strlen(stmt);
ct=ct+2;
ct=parsecondition(stmt,ct,stB,len);
if(stmt[ct]==')')
ct++;
ct=ct+3;
ct=parsecondition(stmt,ct,stS1,len);
if(stmt[ct+1]==';')
{
printf("Parsing the input statement\n");
gen(stB,stS1,stS2,eflag);
return 0;
}
if(stmt[ct]==')')
ct++;

ct=ct+3;

ct=parsecondition(stmt,ct,stS2,len);

ct=ct+2;

if(ct==len)

{

eflag=1;

printf("Parsing the input statement

gen(stB,stS1,stS2,eflag);

return 0;

\n");

SS & CD Lab

22

}

return 0;

}

int parsecondition(char input[],int cntr,char *dest,int tlen)

{

int index=0, pos=0;

while(input[cntr]!='(' && cntr<=tlen) cntr++; if(cntr>=tlen) return 0; index=cntr; while(input[cntr]!=')') cntr++; if(cntr>=tlen) return 0; while(index<=cntr) dest[pos++]=input[index++];

dest[pos]='\0'; return cntr; } void gen(char B[], char S1[], char S2[],int epart) { int Bt=101,Bf=102,Sn=103;
dest[pos]='\0';
return cntr;
}
void gen(char B[], char S1[], char S2[],int epart)
{
int Bt=101,Bf=102,Sn=103;
printf("\nif %s goto %d",B,Bt);
printf("\n\tgoto %d\n",Bf);
printf("%d:",Bt);
printf("%s\n",S1);
if(!epart)
printf("\n%d:\n",Bf);
else
{
printf("goto %d:\n",Sn);
printf("%d: %s\n",Bf,S2);
printf("\n%d:\n",Sn);
}
}

Output:

Format of if statement Example:

if (a<b) then (s=a); if (a>b) then (s=a) else (s=b); Enter the statement

If

(a<b) then (s=a) else (s=b)

Parsing the input statement… If (a<b) goto 101

SS & CD Lab

23

goto 102

101: (s=a)

goto 103

102: (s=b)

103:

2. Write a Yacc program that accepts a regular expression as input and produce its parse tree as output.

expression as input and produce its parse tree as output. %{ #include<stdio.h> #include<ctype.h>

%{ #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<string.h> #define MAX 100 int getREindex(const char *); signed char productions[MAX][MAX]; int count=0,i,j; char temp[MAX+MAX],temp2[MAX+MAX]; %} %token ALPHABET %left '|' %left '.' %nonassoc '*' '+' %% S:re '\n' { printf("This is the rightmost derivation--\n"); for(i=count-1;i>=0;--i) { if(i==count-1) { printf("\nre =>"); strcpy(temp,productions[i]); printf("%s",productions[i]);

}

else { printf("\n => "); j=getREindex (temp);

temp[j]='\0';

sprintf(temp2,"%s%s%s",temp,productions[i],(temp+j+2));

printf("%s",temp2);

strcpy(temp,temp2);

}

}

printf("\n");

exit(0);

}

re:ALPHABET {

SS & CD Lab

24

temp[0]=yylval;temp[1]='\0';

strcpy (productions[count++],temp);

}

|'('re')'

{ strcpy (productions [count++],"(re)");} |re '*'

{ strcpy (productions [count++],"re*");} |re '+'

{ strcpy (productions [count++],"re+");}

|re '|' re strcpy (productions [count++],"re | re");} |re '.' re { { strcpy (productions
|re '|' re
strcpy (productions [count++],"re | re");}
|re '.' re
{
{
strcpy (productions [count++],"re . re");}
;
%%
int main(int argc,char **argv)
{
printf("enter the expression\n");
yyparse();
return 0;
}
yylex()
{
signed char ch=getchar();
yylval=ch;
if(isalpha (ch))
return ALPHABET;
return ch;
}
yyerror()
{
fprintf(stderr,"Invalid Regular Expression!!\n");
exit(1);
}
int getREindex(const char *str)
{
int i=strlen(str)-1;
for(;i>=0;--i){

if(str[i]=='e' && str[i-1]=='r') return i-1;

}

}

SS & CD Lab

25

Output:

[root@localhost ~]# vi cd.y [root@localhost ~]# yacc cd.y [root@localhost ~]# cc y.tab.c [root@localhost ~]# ./a.out enter the expression a+|b* This is the rightmost derivation--

Note: 1) For lex programs vi prognsme.l [a new window will be opened press insert
Note:
1)
For lex programs
vi
prognsme.l
[a new window will be opened press insert key and then start typing.
Esc :wq to save the program.
Lex progname.l
Cc
lex.yy.c –ll
2)
./a.out
[enter the input]
For Yacc Programs
vi
pname.y
yacc pname.y
cc
y.tab.c
3)
./a.out
[enter requires input]
Cd first program: Type program in turbo C with .C extension.
Execute it.

re =>re | re => re | re* => re | b* => re+ | b* => a+ | b*

4)

For shell programs save the file name with .sh extension or just file name without extension as shown below:

vi

pname.sh

or

vi pname

sh

pname.sh

or

sh pname