Top Banner
SS & CD Lab 1 Dept. of CSE KNSIT VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELGAUM - 590014 SS & CD LAB MANUAL VI Sem CSE Prepared by Mrs. RASAGNA REDDY Lecturer DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING K.N.S INSTITUTE OF TECHNOLOGY, BANGALORE -560045 2011-12
25

SS_CD lab manual VTU CSE 6th sem....Rasagna

Oct 24, 2014

Download

Documents

RASAGNA
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 1

Dept. of CSE KNSIT

VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELGAUM - 590014

SS & CD LAB MANUALVI Sem

CSE

Prepared by

Mrs. RASAGNA REDDYLecturer

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

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

2011-12

Page 2: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 2

Dept. of CSE KNSIT

PART – ALEX AND YACC PROGRAMS:Execute the following programs using LEX:

Program 1aProgram 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);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 exNote: 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.outEnter a file name:exThe no.of characters = 40The no.of spaces = 5The no.of lines = 3The no.of words = 7

Page 3: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 3

Dept. of CSE KNSIT

Program 1bProgram 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(){

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 commentThis is not a comment line/* This is a single line comment */Next line is a multi line comment/* This ismulti linecomment */

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

Page 4: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 4

Dept. of CSE KNSIT

This is not a comment lineNext line is a multi line comment

The no.of comment lines = 5

Program 2aProgram 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]+

%%{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.outa+bValidThe operands = a b and count = 2

Page 5: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 5

Dept. of CSE KNSIT

The operators = + and count=1

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

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

%{int flag=0;

%}

%%(" "[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;}. ;%%

int main(){ Printf(“Enter a sentence:\n”);

yylex();if(flag==1)

printf("Compound sentence\n");else

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

}

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

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

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

Page 6: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 6

Dept. of CSE KNSIT

recognize but not identified

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

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

Compound sentence

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

%{int count=0;

%}

SPLCH [!@#$%^&]DIGIT [0-9]LETTER [a-zA-Z]USCORE "_"

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

int main(){

yyin=fopen("ex","r");system(“cat ex”);yylex();fclose(yyin);printf("no of identifiers = %d",count);return 1;

}

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

Page 7: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 7

Dept. of CSE KNSIT

filenamea_sdsdsnodata

no. of identifiers = 5

Execute the following programs using YACC:

Program 4aProgram 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(){

Page 8: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 8

Dept. of CSE KNSIT

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;

}

Output:-[student@localhost ~]# yacc 4a.y[student@localhost ~]# cc y.tab.c[student@localhost ~]# ./a.outa+b*cValida*d+(a-b)*cValid(a*c)*(d+4)Valid-b*Invalid

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

%{#include<stdio.h>#include<ctype.h>

%}

%token letter digit

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

Page 9: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 9

Dept. of CSE KNSIT

|;

other:other letter|other digit|letter|digit;%%

int main(){

yyparse();return 0;

}

int yyerror(){

printf("Error\n");return 0;

}

int yylex(){

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

}

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

Page 10: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 10

Dept. of CSE KNSIT

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

%{#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;

Page 11: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 11

Dept. of CSE KNSIT

}return c;

}

int main(){

yyparse();return 0;

}

int yyerror(){

printf("Error\n");return 0;

}

Output:-[student@localhost ~]# yacc 5a.y[student@localhost ~]# cc y.tab.c[student@localhost ~]# ./a.out4+48[student@localhost ~]# ./a.out12+3*(23-5)66[student@localhost ~]# ./a.out-55+(5*5)-30

Program 5bProgram to recognize strings 'aaab', 'abbb', 'ab', and 'a' using the grammar (anbn ,n>=0).

%{#include<stdio.h>#include<ctype.h>

%}

%token ta tb

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

T:|ta T tb

;

Page 12: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 12

Dept. of CSE KNSIT

%%

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 ~]# vi 5b.y[student@localhost ~]# yacc 5b.y[student@localhost ~]# cc y.tab.c [student@localhost ~]# ./a.outaaabIn valid[student@localhost ~]# ./a.outaaaaabbbbbValidabValid[student@localhost ~]# ./a.outabbbIn valid[student@localhost ~]# ./a.outaError[student@localhost ~]# ./a.out

[no input entered]Valid

Page 13: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 13

Dept. of CSE KNSIT

Program 6Program to recognize the grammar (anb ,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' {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.outaab

Page 14: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 14

Dept. of CSE KNSIT

Error[student@localhost ~]# ./a.outaaaaaaaaaabValidaaaaaaaaaaaaaaaabValidaaaaaaaaaabbbbbbError

PART – BUNIX PROGRAMMING:Program 1aNon-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 ]thenecho "NO ARGUMENTS"elsewhile [ $# -ne 0 ]dox=$1" "$xshiftdoneecho "THE REVERSED STRING IS :$x"fi

Output:

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

Program 1bC 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>

Page 15: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 15

Dept. of CSE KNSIT

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);return 0;}

Output:[student@localhost ~]$ vi mann.c[student@localhost ~]$ cc mann.c[student@localhost ~]$ ./a.outenter the valid unix commandcal May 2012 Su Mo Tu We Th Fr Sa 1 2 3 4 56 7 8 9 10 11 1213 14 15 16 17 18 1920 21 22 23 24 25 2627 28 29 30 31

[student@localhost ~]$ ./a.outenter the valid unix commanddate Tue May 15 15:22:13 EDT 2012[student@localhost ~]$ ./a.outenter the valid unix commandls; 3.c 4b.c 6.y a.c arp.l cht.l first.c kantharaj loka.c man.l oppro.c1 second.c veer1.sh viju1

[student@localhost ~]$ ./a.outenter the valid unix commandpwd/home/student

Page 16: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 16

Dept. of CSE KNSIT

Program 2aShell 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 ]thenecho "no arguments"elif [ ! -e $1 -o ! -e $2 ]thenecho "file doesnot exist"elsep1=`ls -l $1|cut -c2-10`p2=`ls -l $2|cut -c2-10`if [ $p1 == $p2 ]thenecho "file permissions are equal and are $p1"elseecho "file permission are not equal"echo "permission of $1 is $p1"echo "permission of $2 is $p2"fifi

Output:[student@localhost ~]$ sh per.shno arguments[student@localhost ~]$ sh per.sh 3.c 4.cfile permission are not equalpermission of 3.c is rwxrwxrwxpermission of 4.c is rw-rw-r--[student@localhost ~]$ sh per.sh a.c 4.cfile permissions are equal and are rw-rw-r--

Program 2bC 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>

Page 17: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 17

Dept. of CSE KNSIT

#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,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 3aShell 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 ]thenecho "NO ARGUMENTS"exitfiif [ ! -e $1 ]thenecho "given directory does not exist"exitfiecho "the file with maximum length $1 directory is"ls -lR $1 | tr -s " " | cut -d " " -f5 | sort -n | tail -n 1

Page 18: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 18

Dept. of CSE KNSIT

output:[student@localhost ~]$ mkdir kantharaj[student@localhost ~]$ cd kantharaj[student@localhost kantharaj]$ cat > l1kuhf gfhfg[student@localhost kantharaj]$ cat > l2sthj jhbi[student@localhost kantharaj]$ cat > l3jhg8ojhydef lkijdf[student@localhost kantharaj]$ cd ..[student@localhost ~]$ sh vNO ARGUMENTS[student@localhost ~]$ sh v kantharajthe file with maximum lengthkantharaj directory is19

Program 3bC 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");elsefor(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]);elseif(S_ISCHR(s.st_mode))printf("%s is a character device file \n",argv[i]);elseif(S_ISBLK(s.st_mode))printf("%s is a block device file\n",argv[i]);

Page 19: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 19

Dept. of CSE KNSIT

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

output:

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

Program 4aShell 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 $*doif [ ! -f $i ]thenecho "$i doesnot exist ">/dev/ttyfiecho "echo $i is created"echo "cat>$i<<end"cat $iecho "end"done

output:[student@localhost ~]$ sh 4a.shto unbundle sh this file[student@localhost ~]$ cat>f1sdfqw4e5 [Press Ctrl+D][student@localhost ~]$ cat>f2etr235edrf [Press Ctrl+D][student@localhost ~]$ cat>f3erre5t45y [Press Ctrl+D][student@localhost ~]$ sh 4a.sh f1 f2 f3> zip[student@localhost ~]$ mkdir rasagna[student@localhost ~]$ cd rasagna

Page 20: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 20

Dept. of CSE KNSIT

[student@localhost rasagna]$ sh ../zip../zip: line 1: to: command not foundf1 is createdf2 is createdf3 is created

Program 4bC 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;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 PROCESSchild process id is 2389parent process id is 2388IN PARENT PROCESSchild process id is 2389parent process id is 2388

Page 21: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 21

Dept. of CSE KNSIT

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 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.....\n");gen(stB,stS1,stS2,eflag);return 0;

Page 22: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 22

Dept. of CSE KNSIT

}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;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 statementExample:if (a<b) then (s=a);if (a>b) then (s=a) else (s=b);Enter the statementIf (a<b) then (s=a) else (s=b)

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

Page 23: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 23

Dept. of CSE KNSIT

goto 102101: (s=a)goto 103102: (s=b)103:

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

%{#include<stdio.h>#include<ctype.h>#include<stdlib.h>#include<string.h>#define MAX 100int 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 {

Page 24: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 24

Dept. of CSE KNSIT

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 [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;}}

Page 25: SS_CD lab manual VTU CSE 6th sem....Rasagna

SS & CD Lab 25

Dept. of CSE KNSIT

Output:

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

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

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.lCc lex.yy.c –ll./a.out[enter the input]

2) For Yacc Programsvi pname.yyacc pname.ycc y.tab.c./a.out[enter requires input]

3) Cd first program: Type program in turbo C with .C extension.Execute it.

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 pnamesh pname.sh or sh pname