0% found this document useful (0 votes)
38 views30 pages

System Software Programming Exercises

The document outlines a series of practical experiments related to system software, focusing on programming tasks such as implementing a lexical analyzer, left factoring grammar, removing left recursion, and creating recursive descent and predictive parsers. Each experiment includes a program example, explanations of concepts, and exercises for further practice. The document serves as a guide for students to understand and apply various compiler design techniques.

Uploaded by

sanket1954c
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views30 pages

System Software Programming Exercises

The document outlines a series of practical experiments related to system software, focusing on programming tasks such as implementing a lexical analyzer, left factoring grammar, removing left recursion, and creating recursive descent and predictive parsers. Each experiment includes a program example, explanations of concepts, and exercises for further practice. The document serves as a guide for students to understand and apply various compiler design techniques.

Uploaded by

sanket1954c
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

System Software (3160715))

[Link]. Experiment Page no Date Signature

1. Write a program to print the content


of file and display file content using file
pointer

2. Write a program to implement the Lexical


analyzer
.

3. Write a program to left factor the given


grammar.

4. Write a program to remove the Left Recursion


from a given grammar

5. Implement Recursive Descendant Parsing


for the given Grammar.
E -> T + E / T
T -> F * T / F
F -> ( E ) / i

6. Implement Predictive Parser for the grammar.


T -> F * T / F
F -> ( E ) / i
E -> T + E / T

7. Write a SAL program in text file and


generate SYMTAB and LITTAB

8. Use macro features of C language.

9. Write a program which generates Quadruple


Table for the given postfix String.

10. Write a C program to parse a given using Predictive


parsing for given grammar.
type → simple | ↑id | array
[ simple type simple → integer | char | num
dot dot num

KITRC, Kalol Page No.| 1


System Software (3160715))

Practical # 1
Aim: What is Lexical Analyzer? How it is used? Write a
program to implement Lexical Analyzer.
Introduction:
1. What is Lexical Analyzer?
Answer: Lexical Analyzer is a function in which the stream of characters making up the source
program is read from left to right and grouped into tokens that are sequences of characters having a
collective meaning.

2. How Lexical Analyzer is used?


Answer:Tokens are defined often by regular expressions, which are understood by a Lexical
Analyzer generator such as Lex. The Lexical Analyzer (generated automatically by a tool like Lex,
or hand-crafted) reads in a stream of characters, identifies the lexemes in the stream, and
categorizes them into tokens.

Advantages:
Simple Design: As Lexical Analyzer is separated from other analysis phases of compilation;
its design becomes simpler and easy to implement. Compiler efficiency and portability is improved.

Disadvantages:
A large amount of time is spent in reading the source program and partitioning it into tokens.
So specialized buffering techniques for reading input characters and processing tokens need to be
applied to speed up compiler. One more disadvantage is that the lexical Analyzer needs to read the
whole symbol table every time an identifier is encountered in the source code.

Applications:
Removal of White Spaces and comments, Recognizing Identifiers and Keywords,
Recognizing Constants, etc.

Program:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
void keyw(char *p);
int i=0,id=0,kw=0,num=0,op=0;
char keys[33][11]={"main","auto","break","case","char","const","continue","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
main()
{
char ch,str[25],seps[15]=" \t\n,;(){}[]#\"<>",oper[]="!%^&*-+=~|.<>/?";

KITRC, Kalol Page No.| 2


System Software (3160715))

int j;
char fname[50];
FILE *f1;
//clrscr();
f1 = fopen("[Link]","r");
//f1 = fopen("Input","r");
if(f1==NULL)
{
printf("file not found");
exit(0);
}
while((ch=fgetc(f1))!=EOF)
{
for(j=0;j<=14;j++)
{
if(ch==oper[j])
{
printf("%c is an operator\n",ch);
op++;
str[i]='\0';
keyw(str);
}
}
for(j=0;j<=14;j++)
{
if(i==-1)
break;
if(ch==seps[j])
{
if(ch=='#')
{
while(ch!='>')
{
printf("%c",ch);
ch=fgetc(f1);
}
printf("%c is a header file\n",ch);
i=-1;
break;
}
if(ch=='"')
{
do
{
ch=fgetc(f1);
printf("%c",ch);
}while(ch!='"');
printf("\b is an argument\n");

KITRC, Kalol Page No.| 3


System Software (3160715))

i=-1;
break;
}
str[i]='\0';
keyw(str);
}
}
if(i!=-1)
{
str[i]=ch;
i++;
}
else
i=0;
}
printf("Keywords: %d\nIdentifiers: %d\nOperators: %d\nNumbers: %d\n",kw,id,op,num);
//getch();
}
void keyw(char *p)
{
int k,flag=0;
for(k=0;k<=31;k++)
{
if(strcmp(keys[k],p)==0)
{
printf("%s is a keyword\n",p);
kw++;
flag=1;
break;
}
}
if(flag==0)
{
if(isdigit(p[0]))
{
printf("%s is a number\n",p);
num++;
}
else
{
//if(p[0]!=13&&p[0]!=10)
if(p[0]!='\0')
{
printf("%s is an identifier\n",p);
id++;
}
}
}

KITRC, Kalol Page No.| 4


System Software (3160715))

i=-1;
}
Output:

Exercise

[Link] is Lexical Analyzer?

KITRC, Kalol Page No.| 5


System Software (3160715))

Practical # 2
Aim:Write a Lexical Analyzer (using lex utility for UNIX).

[Link] file:
%{
#include <stdio.h>
int regs[26];
int base;
%}
%start list
%token DIGIT LETTER
%left '|'
%left '&'
%left '+''-'
%left '*''/''%'
%left UMINUS /*supplies precedence for unary minus */
%% /* beginning of rules section */
list: /*empty */
|
list stat '\n'
|
list error '\n'
{
yyerrok;
}
;
stat: expr
{
printf("%d\n",$1);
}
|
LETTER '=' expr
{
regs[$1] = $3;
}
;
expr: '(' expr ')'
{
$$ = $2;
}
|
expr '*' expr
{
$$ = $1 * $3;
}

KITRC, Kalol Page No.| 6


System Software (3160715))

|
expr '/' expr
{
$$ = $1 / $3;
}
|
expr '%' expr
{
$$ = $1 % $3;
}
|
expr '+' expr
{
$$ = $1 + $3;
}
|
expr '-' expr
{
$$ = $1 - $3;
}
|
expr '&' expr
{
$$ = $1 & $3;
}
|
expr '|' expr
{
$$ = $1 | $3;
}
|
'-' expr %prec UMINUS
{
$$ = -$2;
}
|
LETTER
{
$$ = regs[$1];
}
|
number
;
number: DIGIT
{
$$ = $1;
base = ($1==0) ? 8 : 10;
} |

KITRC, Kalol Page No.| 7


System Software (3160715))

number DIGIT
{
$$ = base * $1 + $2;
}
;
%%
main()
{
return(yyparse());
}
yyerror(s)
char *s;
{
fprintf(stderr, "%s\n",s);
}
yywrap()
{
return(1);
}

[Link] file:
%{
#include <stdio.h>
#include "[Link].h"
int c;
extern int yylval;
%}
%%
""
;[a-z]
{
c = yytext[0];
yylval = c - 'a';
return(LETTER);
}
[0-9]
{
c = yytext[0];
yylval = c - '0';
return(DIGIT);
}
[^a-z0-9\b]
{
c = yytext[0];
return(c);
}

KITRC, Kalol Page No.| 8


System Software (3160715))

Compiling the Example Program:


yacc -d [Link]
Use the li command to verify that the following files were created:
[Link].c->The C language source file that the yacc command created for the parser.
[Link].h->A header file containing define statements for the tokens used by the parser.

Process the lex specification file:


lex [Link]
Use the li command to verify that the following file was created:
[Link].c->The C language source file that the lex command created for the lexical analyzer.

Compile and link the two C language source files:


cc [Link].c [Link].c
Use the li command to verify that the following files were created:
[Link].o->The object file for the [Link].c source file
[Link].o->The object file for the [Link].c source file
[Link]->The executable program file

To then run the program directly from the [Link] file, enter:
$ [Link]
Or, to move the program to a file run it, enter:
$ mv [Link] example
$ example
When you press the Enter key, the program displays the result of the operation. After you assign a
value to a variable:
• m=4 <enter>
• _
the cursor moves to the next line. When you use the variable in subsequent calculations, it will have
the assigned value:
• m+5 <enter>
• 9

KITRC, Kalol Page No.| 9


System Software (3160715))

Practical # 3
Aim:Write a program to left factor the given grammar.

Program:
#include<stdio.h>
#include<string.h>
int main()
{
char gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],tempGram[20];
int i,j=0,k=0,l=0,pos;
printf("Enter Production : A->");
gets(gram);
for(i=0;gram[i]!='|';i++,j++)
part1[j]=gram[i];
part1[j]='\0';
for(j=++i,i=0;gram[j]!='\0';j++,i++)
part2[i]=gram[j];
part2[i]='\0';
for(i=0;i<strlen(part1)||i<strlen(part2);i++)
{
if(part1[i]==part2[i])
{
modifiedGram[k]=part1[i];
k++;
pos=i+1;
}
}
for(i=pos,j=0;part1[i]!='\0';i++,j++)
{
newGram[j]=part1[i];
}
newGram[j++]='|';
for(i=pos;part2[i]!='\0';i++,j++){
newGram[j]=part2[i];
}
modifiedGram[k]='X';
modifiedGram[++k]='\0';
newGram[j]='\0';
printf("\n A->%s",modifiedGram);
printf("\n X->%s\n",newGram);
}

Output:

KITRC, Kalol Page No.| 10


System Software (3160715))

EXCERCISE:
1. Write down a program to generate following output of given input.
Input: S=iEiSeS | iEts|b

KITRC, Kalol Page No.| 11


System Software (3160715))

Practical # 4
Aim: Write a program to remove the Left Recursion from a
given grammar.

Program:

#include<stdio.h>
#include<string.h>
void main() {
char input[100],*l,*r,*temp,tempprod[20],productions[25][50];
int i=0,j=0,flag=0;
printf("Enter the productions: ");
scanf("%s",input);
l = strtok(input,"->");
r = strtok(NULL,"->");
temp = strtok(r,"|");
while(temp) {
if(temp[0] == l[0]) {
flag = 1;
sprintf(productions[i++],"%s'->%s%s'\0",l,temp+1,l);
}
else
sprintf(productions[i++],"%s->%s%s'\0",l,temp,l);
temp = strtok(NULL,"|");
}
sprintf(productions[i++],"%s->\356\0",l);
if(flag == 0)
printf("The given productions don't have Left Recursion");
else
for(j=0;j<i;j++) {
printf("\n%s",productions[j]);
}
}

KITRC, Kalol Page No.| 12


System Software (3160715))

Output:

EXCERCISE: Remove left recursion from the following input Input:- E→EA/A,
A→AT/a,
T→a, E->1

KITRC, Kalol Page No.| 13


System Software (3160715))

Practical # 5
Aim: Implement Recursive Descendent Parsing for the given
Grammar.
E -> T + E / T
T -> F * T / F
F -> ( E ) / i

Program:
#include <stdio.h>
#include <conio.h>
char input[100];
char prod[100][100];
int pos=-1,l,st=-1;
char id,num;
void E();
void T();
void F();
void advance();
void Td();
void Ed();
void advance()
{
pos++;
if(pos<l)
{
if(input[pos]>='0'&& input[pos]<='9')
{
num=input[pos];
id='\0';
}
if((input[pos]>='a' || input[pos]>='A')&&(input[pos]<='z' || input[pos]<='Z'))
{id=input[pos];
num='\0';
}
}
}
void E()
{
strcpy(prod[++st],"E->TE'");
T();
Ed();

KITRC, Kalol Page No.| 14


System Software (3160715))

}
void Ed()
{
int p=1;
if(input[pos]=='+')
{
p=0;
strcpy(prod[++st],"E'->+TE'");
advance();
T();
Ed();
}
if(input[pos]=='-')
{ p=0;
strcpy(prod[++st],"E'->-TE'");
advance();
T();
Ed();
}

if(p==1)
{
strcpy(prod[++st],"E'->null");
}
}

void T()
{
strcpy(prod[++st],"T->FT'");
F();
Td();
}
void Td()
{
int p=1;
if(input[pos]=='*')
{
p=0;
strcpy(prod[++st],"T'->*FT'");
advance();
F();
Td();
}
if(input[pos]=='/')
{ p=0;
strcpy(prod[++st],"T'->/FT'");
advance();
F();

KITRC, Kalol Page No.| 15


System Software (3160715))

Td();
}
if(p==1)
strcpy(prod[++st],"T'->null");
}
void F()
{
if(input[pos]==id) {
strcpy(prod[++st],"F->id");
advance(); }
if(input[pos]=='(')
{
strcpy(prod[++st],"F->(E)");
advance();
E();
if(input[pos]==')') {
//strcpy(prod[++st],"F->(E)");
advance(); }
}
if(input[pos]==num)
{
strcpy(prod[++st],"F->num");
advance();
}
}
int main()
{
int i;
printf("Enter Input String ");
scanf("%s",input);
l=strlen(input);
input[l]='$';
advance();
E();
if(pos==l)
{
printf("String Accepted\n");
for(i=0;i<=st;i++)
{
printf("%s\n",prod[i]);
}
}
else
{
printf("String rejected\n");
}
getch();
return 0;

KITRC, Kalol Page No.| 16


System Software (3160715))

}
Output (With accepted string):

Output (With not accepted string):

EXCERCISE:Write down a program to generate the recursive descent


parser fromthe given grammar. E→iE’,
E’->+iE’|epsilon

KITRC, Kalol Page No.| 17


System Software (3160715))

Practical # 6
Aim: Implement Predictive Parser for the given grammar.
E -> T + E / T
T -> F * T / F
F -> ( E ) / i

Program:
#include<string.h>
#include<conio.h>
char a[10];
int top=-1,i;
void error(){
printf("Syntax Error");
}
void push(char k[])
{
for(i=0;k[i]!='\0';i++)
{
if(top<9)
a[++top]=k[i];
}
}
char TOS()
{
return a[top];
}
void pop()
{
if(top>=0)
a[top--]='\0';
}
void display()
for(i=0;i<=top;i++)
printf("%c",a[i]);
}
void display1(char p[],int m)
{
int l;
printf("\t");
for(l=m;p[l]!='\0';l++)
printf("%c",p[l]);
}

KITRC, Kalol Page No.| 18


System Software (3160715))

char* stack(){
return a;
}
int main()
{
char ip[20],r[20],st,an;
int ir,ic,j=0,k,counter=0;
char t[5][6][10]={"$","$","TH","$","TH","$",
"+TH","$","e","e","$","e",
"$","$","FU","$","FU","$",
"e","*FU","e","e","$","e",
"$","$","(E)","$","i","$"};
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();

KITRC, Kalol Page No.| 19


System Software (3160715))

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=='$'){
counter++;
break;}
if(TOS()=='$'){
error();
break;
}
}
k=strcmp(stack(),"$");
if(counter==1)
printf("\n Given String is accepted");
else
printf("\n Given String is not accepted");
return 0;
}

Output (With accepted string):

KITRC, Kalol Page No.| 20


System Software (3160715))

Output (With not accepted string):

KITRC, Kalol Page No.| 21


System Software (3160715))

Practical # 7
Aim:Write a SAL program in text file and generate SYMTAB
and LITTAB.

SYMTABProgram:
#include<stdio.h>
#include<conio.h>
struct intermediate
{
int addr;
char label[10];
char mnem[10];
char op[10];
}res;
struct symbol
{
char symbol[10];
int addr;
}sy;
void main()
{
FILE *s1,*p1;
clrscr();
s1=fopen("[Link]","r+");
p1=fopen("[Link]","w");
while(!feof(s1))
{
fscanf(s1,"%d %s %s %s",&[Link],[Link],[Link],[Link]);
if(strcmp([Link],"NULL")!=0)
{
strcpy([Link],[Link]);
[Link]=[Link];
fprintf(p1,"%s\t%d\n",[Link],[Link]);
}
}
fcloseall();
printf("symbol table created");
getch();
}

Input file:

KITRC, Kalol Page No.| 22


System Software (3160715))

[Link]:
0 NULL START 500
500 A DS 100
600 B DC 10
610 FIRST PRINT A
612 NULL READ B
613 NULL END FIRST

Output:

Output file:
[Link]:
A 500
B 600
FIRST 610

LITTABProgram:
#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
FILE *fp;
char ch,d,l[10];
int i=0,j=0;
clrscr();
fp=fopen("[Link]","r");
printf("literal table\n\nliteral value\t address\n");
do
{
ch=fgetc(fp);
if(ch=='=')
{
ch=fgetc(fp);
while(ch!=''&& ch!='\n'&& ch!=EOF && ch!='\t')
{ l[j]=ch; printf( "%c",ch); ch=fgetc(fp); j++; }
l[j]='\0';
printf("\t\t%x",i+2);
printf("\n");
if((strlen(l))>=7)
{ i=i+4; }

KITRC, Kalol Page No.| 23


System Software (3160715))

else
{ i=i+3; }
j=0;
}
} while(ch!=EOF);
fclose(fp);
getch();
}

Input file:
[Link]:
start
ida=x'057'
sta=k'0234'
stl=c'EOF'
end

Output:

EXERCISE :
1. What is Symbol table?

2. what is assembler ?

KITRC, Kalol Page No.| 24


System Software (3160715))

Practical # 8
Aim:Use macro features of C language.

Program:
#include <stdio.h>
#include <stdlib.h>
#define equation(a) (a/65)
int main()
{
float x,y;
printf("convert rupees to dollar:");
printf("\nenter the rupees:");
scanf("%f",&x);
y=equation(x);
printf("the value in dollar: %f",y);
return 0;
}

Output:

EXCERCISE:
1. What is the use of macro expansion counter?

KITRC, Kalol Page No.| 25


System Software (3160715))

Practical # 9
Aim: Write a program which generates Quadruple Table for
the given postfix String.

Program:
#include<stdio.h>
void main()
{
char quar[20][4];
char str[10];
int i=0,q_i=0,j,temp=65;
printf("Enter the string:");
scanf("%s",&str[i]);
while(str[i]!='\0'){
if(str[i]=='+' || str[i]=='*' || str[i]=='+/')
{
quar[q_i][0]=str[i];
quar[q_i][1]=str[i-2];
quar[q_i][2]=str[i-1];
quar[q_i][3]=temp;
str[i-2]=temp;
temp++;
q_i++;
j=i;
i=0;
j++;
while(str[j]!='\0')
{
str[j-2]=str[j];
j++;
}
str[j-2]='\0';
}
else
{
i++;
}
}
for(i=0;i<q_i;i++){
printf("\n%c\t%c\t%c\t%c\n",quar[i][0],quar[i][1],quar[i][2],quar[i][3]);
}
}
Output:

KITRC, Kalol Page No.| 26


System Software (3160715))

1, Consider the input statement x:= -a*b + -a*b Generate quadruple table

KITRC, Kalol Page No.| 27


System Software (3160715))

Practical # 10
Aim:Write a C program to parse a given string using
Predictive parsing for given grammar.
type → simple | ↑id | array [ simple ] of type
simple → integer | char | num dotdot num

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int next;
char str[100];
char token[100],look_ahead[80],c;
void Next_Token();
void Terminals();
void main(){
FILE *f1;
clrscr();
printf("The grammar is : ");
f1=fopen("[Link]","r");
printf("\n");
while((c=fgetc(f1))!=EOF){
printf("%c",c);
}
printf("\nEnter any string: ");
gets(str);
Next_Token();
Terminals();
printf("\nCongratulation Successful Parsing of the Given String\n");
getch();
}
void Error_State(){
printf("\n\nERROR : UNSUCCESSFUL PARSING \n");
getch();
exit(0);
}
void Next_Token(){
int i,j=0;
for(i=next;str[i]!=''&& str[i]!='\0';i++){
look_ahead[j++]=str[i];
//j++;
next++;
}
next++;

KITRC, Kalol Page No.| 28


System Software (3160715))

look_ahead[j]='\0';
}
void Match(char token[])
{
if(strcmp(look_ahead,token)==0)
Next_Token();
else
Error_State();
}
void Simple(){
if(strcmp(look_ahead,"int")==0)
Match("int");
else if(strcmp(look_ahead,"char")==0)
Match("char");
else if(strcmp(look_ahead,"num")==0)
{
Match("num");
Match("..");
Match("num");
}
else
Error_State();
}
void Terminals(){
if(strcmp(look_ahead,"int")==0 || strcmp(look_ahead,"char")==0 ||
strcmp(look_ahead,"num")==0)
Simple();
else{
if(strcmp(look_ahead,"^")==0){
Match("^");
Match("id");
}
else{
if(strcmp(look_ahead,"array")==0){
Match("array");
Match("[");
Simple();
Match("]");
}
else{
Error_State();
}
}
}
}

Input file:

KITRC, Kalol Page No.| 29


System Software (3160715))

[Link]:
type=simple|^ id|array [ simple ]
simple=int|char|num..num

Output (Successful Parsing):

Output (Unuccessful Parsing):

EXERCISE
[Link] is predictive parser?

KITRC, Kalol Page No.| 30

You might also like