0% found this document useful (0 votes)
13 views

cd lab programs only

The document contains a list of programming tasks related to compiler design, including token separation, symbol table implementation, and lexical analysis using various tools like Lex and YACC. Each task is accompanied by C code implementations that demonstrate the functionality required for each program. The document serves as a guide for understanding and implementing fundamental concepts in compiler construction.

Uploaded by

merichfakeid1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

cd lab programs only

The document contains a list of programming tasks related to compiler design, including token separation, symbol table implementation, and lexical analysis using various tools like Lex and YACC. Each task is accompanied by C code implementations that demonstrate the functionality required for each program. The document serves as a guide for understanding and implementing fundamental concepts in compiler construction.

Uploaded by

merichfakeid1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

INDEX

S.NO Program Page No.

1 program to design token separator for the given expression.

2 program to implement a symbol table.

3 program to develop a lexical analyzer to recognize a few patterns.

4 program to develop a lexical analyzer using Lex tool.

5 program to recognize a valid arithmetic expression using YACC.

6 program to recognize a valid variable name using YACC.

7 program to implement calculator using Lex and YACC.

8 program for implementing type checking for given expression.

9 program to convert the BNF rules into YACC.

10 program to implement data flow and control flow analysis.

11 program to implement stack storage allocation strategies.

12 program to implement heap storage allocation strategies.

13 program to construct a directed acyclic graph (DAG).

14 program to implement the back end of the compiler.

15 program to implement simple code optimization technique.

program to implement simple code optimization technique using do-


16
while.
1

1. program to design token separator for the given expression


#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
int main()
{
char exp[50] = "\0", con[50] = "\0", kwd[50] = "\0", id[50] = "\0", sym[50] = "\0", opr[50] = "\0";
char key[6][10] = { "if", "for", "do", "while", "int", "float" };
char ch;
char ptr[10][10] = { "\0" };
int i = 0, j = 0, k = -1, n = -1, p = -1, s = -1;
// clrscr();
puts("enter the expression for lexical analysis...\n");
gets(exp);
puts("\nthe tokens are...");
do
{
ch = exp[i];
if (isalpha(ch))
{
k = -1;
ptr[++n][++k] = ch;
i++;
ch = exp[i];
if (isalpha(ch) || isdigit(ch))
{
while (isalpha(ch) || isdigit(ch))
{
ptr[n][++k] = ch;
i++;
ch = exp[i];
}
while (j < 6)
{
if (strcmp(key[j], ptr[n]) == 0)
{
ptr[n][++k] = ' ';
strcat(kwd, ptr[n]);
break;
}
if (j == 5)
{
ptr[n][++k] = ' ';
strcat(id, ptr[n]);
}
j++;
}
}
else
{
ptr[n][++k] = ' ';
strcat(id, ptr[n]);
}
i--;
ch = exp[i];
j = 0;
}
else if (isdigit(ch))
{
k = -1;
ptr[++n][++k] = ch;
2

i++;
ch = exp[i];
if (isdigit(ch))
{
while (isdigit(ch))
{
ptr[n][++k] = ch;
i++;
ch = exp[i];
}
}
i--;
ch = exp[i];
ptr[n][++k] = ' ';
strcat(con, ptr[n]);
}
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '>' || ch == '<' || ch == '=' || ch == '!')
{
opr[++p] = ch;
i++;
ch = exp[i];
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '>' || ch == '<' || ch == '=' || ch == '!')
{
opr[++p] = ch;
}
else
{
i--;
ch = exp[i];
opr[++p] = ' ';
}
}
else
{
sym[++s] = ch;
sym[++s] = ' ';
}
i++;
} while (exp[i] != '\0');

puts("\nKeywords..\n");
puts(kwd);
puts("\nIdentifiers..\n");
puts(id);
puts("\nConstants..\n");
puts(con);
puts("\nOperators..\n");
puts(opr);
puts("\nSymbols..\n");
puts(sym);
//getch();
return 0;
}
3

Output-1:
4

2. program to implement a symbol table.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>

typedef struct node Node;


typedef unsigned int uint;

struct node {
char symb[40];
char type[10];
char strg[10];
uint addr;
Node *next;
};

Node *First = NULL, *p;

void Create() {
Node *Last = NULL;
char ch;
do {
printf("Enter Symbol, type, storage class & address [0 & 65535] ...\n");
p = (Node*) malloc(sizeof(Node));
if (!p) {
printf("Memory allocation failed!\n");
return;
}
scanf("%s %s %s %u", p->symb, p->type, p->strg, &(p->addr));
p->next = NULL;

if (First == NULL)
First = p;
else
Last->next = p;

Last = p;

// FIX: Properly read user input with a space before %c to consume newline
printf("One more Symbol [y/n] : ");
scanf(" %c", &ch); // Ensure the space before %c to remove the newline issue

} while (ch == 'y' || ch == 'Y'); // Case-insensitive check


}

void Display() {
if (First == NULL)
printf("Symbol Table is Empty ...\n");
else {
printf("Symbols in the Table:\n");
printf("--------------------------------------------------\n");
printf(" Symbol Type StorageClass Address\n");
printf("--------------------------------------------------\n");
for (p = First; p != NULL; p = p->next)
printf("%10s %10s %10s\t%u\n", p->symb, p->type, p->strg, p->addr);
printf("--------------------------------------------------\n");
}
}
5

void Destroy() {
while (First != NULL) {
p = First;
First = First->next;
free(p);
}
}

void Search() {
char sym[10];
printf("Enter Symbol ...\n");
scanf("%s", sym);

for (p = First; p != NULL; p = p->next) {


if (strcmp(p->symb, sym) == 0)
break;
}

if (p == NULL)
printf("Symbol does not exist in the table.\n");
else {
printf(" Symbol = %s\n", p->symb);
printf(" Type = %s\n", p->type);
printf(" Storage Class = %s\n", p->strg);
printf(" Address = %u\n", p->addr);
}
}

void Insert() {
Node *t;
char sym[40];
printf("Enter Symbol ...\n");
scanf("%s", sym);

for (p = First; p != NULL; p = p->next) {


if (strcmp(p->symb, sym) == 0)
break;
}

if (p != NULL)
printf("Multiple Declaration.\n");
else {
p = (Node*) malloc(sizeof(Node));
strcpy(p->symb, sym);
printf("Enter type, storage class & address [0 & 65535] ...\n");
scanf("%s %s %u", p->type, p->strg, &(p->addr));
p->next = NULL;

for (t = First; t->next != NULL; t = t->next);


t->next = p;
}
}

void Delete() {
Node *t;
char sym[40];
printf("Enter Symbol ...\n");
scanf("%s", sym);

p = NULL;
t = First;
do {
if (strcmp(t->symb, sym) == 0)
6

break;
p = t;
t = t->next;
} while (t != NULL);

if (t == NULL)
printf("Symbol does not exist.\n");
else {
if (t == First)
First = First->next;
else
p->next = t->next;
free(t);
printf("Symbol Deleted Successfully.\n");
}
}

int main() {
int ch;
do {
printf("Symbol Table Operations Menu\n");
printf("-----------------------------\n");
printf("1. Create the Symbol Table\n");
printf("2. Display the Symbol Table\n");
printf("3. Insert a Symbol\n");
printf("4. Delete a Symbol\n");
printf("5. Search for a Symbol\n");
printf("6. Destroy the Table\n");
printf("7. Exit\n\n");
printf("Your Choice [1..7] ? : ");
scanf("%d", &ch);

switch (ch) {
case 1: Create(); break;
case 2: Display(); break;
case 3: Insert(); break;
case 4: Delete(); break;
case 5: Search(); break;
case 6: Destroy(); break;
case 7: break;
default: printf("Invalid Choice ..."); getch();
}
} while (ch != 7);
}
7

Output-2:
8

3. program to develop a lexical analyzer to recognize a few patterns.

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>

int main()
{
FILE *fi, *fo, *fop, *fk;
int flag = 0, i = 1;
char c, t, a[15], ch[15], file[20];

// printf("\n Enter the File Name:");


// scanf("%s", &file);
// fi = fopen(file, "r");

fi = fopen("input.c", "r");
fo = fopen("inter.c", "w");
fop = fopen("oper.c", "r");
fk = fopen("key.c", "r");

c = getc(fi);
while (!feof(fi))
{
if (isalpha(c) || isdigit(c) || (c == '[' || c == ']' || c == '.' == 1))
fputc(c, fo);
else
{
if (c == '\n')
fprintf(fo, "\t$\t");
else
fprintf(fo, "\t%c\t", c);
}
c = getc(fi);
}

fclose(fi);
fclose(fo);

fi = fopen("inter.c", "r");
printf("\n Lexical Analysis");
fscanf(fi, "%s", a);
printf("\n Line: %d\n", i++);

while (!feof(fi))
{
if (strcmp(a, "$") == 0)
{
printf("\n Line: %d \n", i++);
fscanf(fi, "%s", a);
}

fscanf(fop, "%s", ch);


while (!feof(fop))
{
if (strcmp(ch, a) == 0)
{
fscanf(fop, "%s", ch);
printf("\t\t%s\t:\t%s\n", a, ch);
flag = 1;
9

}
fscanf(fop, "%s", ch);
}
rewind(fop);

fscanf(fk, "%s", ch);


while (!feof(fk))
{
if (strcmp(ch, a) == 0)
{
fscanf(fk, "%s", ch);
printf("\t\t%s\t:\tKeyword\n", a);
flag = 1;
}
fscanf(fk, "%s", ch);
}
rewind(fk);

if (flag == 0)
{
if (isdigit(a[0]))
printf("\t\t%s\t:\tConstant\n", a);
else
printf("\t\t%s\t:\tIdentifier\n", a);
}

flag = 0;
fscanf(fi, "%s", a);
}

getch();
}

Input.c:

#include <stdio.h>
int main()
{
int a=10, b=20, c;

c = a + b;
printf ("Sum is %d", c);
return 0;
}

Inter.c:
#include <stdio.h>

int main()
{
int a = 10,
b = 20,
c;

c = a + b;
printf("Sum is %d", c);

return 0;
}
10

Oper.c: Key.c:
+
Addition
- auto
Subtraction break
* case
Multiplication char
/
const
Division
= continue
Assignment default
== do
Equality double
!= else
Not Equal
enum
<
Less Than extern
> float
Greater Than for
<= goto
Less Than or Equal
if
>=
Greater Than or Equal int
++ long
Increment register
-- return
Decrement
short
&&
Logical AND signed
|| sizeof
Logical OR static
! struct
Logical NOT switch
&
typedef
Bitwise AND
| union
Bitwise OR unsigned
^ void
Bitwise XOR volatile
~
while
Bitwise Complement
<<
Left Shift
>>
Right Shift
?
Ternary Conditional
:
Colon
;
Semicolon
,
Comma
.
Dot
()
Parentheses
[]
Brackets
{}
Braces
11

Output-3:
12

4. program to develop a lexical analyzer using Lex tool.

letter [a-zA-Z]
digit [0-9]

%%

{digit}+("E"("+"|"-")?{digit}+)?
printf("\n%s\tis real number", yytext);

{digit}+"."{digit}+("E"("+"|"-")?{digit}+)?
printf("\n%s\t is floating pt no ", yytext);

"if"|"else"|"int"|"char"|"scanf"|"printf"|"switch"|"return"|"struct"|"do"|"while"|"void"|"for"|"float"
printf("\n%s\t is keywords", yytext);

"\a"|"\\n"|"\\b"|"\t"|"\\t"|"\b"|"\\a"
printf("\n%s\tis Escape sequences", yytext);

{letter}({letter}|{digit})*
printf("\n%s\tis identifier", yytext);

"&&"|"<"|"">"|"<="|">="|"="|"+"|"-"|"?"|"*"|"/"|"%"|"&"|"||"
printf("\n%s\toperator ", yytext);

"{"|"}"|"["|"]"|"("|")"|"#"|"'"|"."|"\""|"\\"|";"|","
printf("\n%s\t is a special character", yytext);

"%d"|" %s"|" %c"|" %f"|" %e"


printf("\n%s\tis a format specifier", yytext);

%%

int yywrap()
{
return 1;
}

int main()
{
yyin = fopen("test.c", "r");
yylex();
getch();
fclose(yyin);
return 0;
}

Output-4 :
13

5. program to recognize a valid arithmetic expression using YACC.

Lex File :

%{
#include "y.tab.h"
%}
%%
[0-9]+(\.[0-9]+)? { return NUM; }

[a-zA-Z_][_a-zA-Z0-9]* { return ID; }

[\t] ;

\n return 0;

. return yytext[0];
%%
yywrap() { }

Yacc File :

%{
#include<stdio.h>
#include<stdlib.h>
%}

%token NUM ID
%left '+'
%left '*' '/'

%%
e: e '+' e
| e '-' e
| e '*' e
| e '/' e
| '(' e ')'
| NUM
;

%%

main()
{
printf("enter the expression...\n");
yyparse();
getch();
}

yyerror()
{
printf("invalid expression\n");
getch();
exit(0);
}
14

Output-5
15

6. program to recognize a valid variable name using YACC.

Lex File :

%{
#include"y.tab.h"
%}

%%
[a-zA-Z] { return LETTER; }
[0-9] { return DIGIT; }
[_] { return UND; }
[\n] { return NL; }
. { return yytext[0]; }
%%

Yacc File :

%{
#include<stdio.h>
#include<stdlib.h>
%}

%token DIGIT LETTER UND NL

%%

stmt: variable NL { printf("valid identifiers\n"); getch(); exit(0); }


;

variable: LETTER alphanumeric


;

alphanumeric: LETTER alphanumeric


| DIGIT alphanumeric
| UND alphanumeric
| LETTER
| DIGIT
| UND
;

%%

int yywrap(void)
{
return 0;
}

int yyerror(char *msg)


{
printf("Invalid variable\n");
getch();
exit(1);
}

int main()
{
16

printf("enter the variable: \n");


yyparse();
getch();
return 0;
}

Output-6 :
17

7. program to implement calculator using Lex and YACC.

Lex File :
%{
#include"y.tab.h"
#include<math.h>
extern int yylval;
%}

%%
[0-9]+ { yylval = atoi(yytext); return NUM; }
[+] { return '+'; }
[-] { return '-'; }
[*] { return '*'; }
[/] { return '/'; }
[\t]+ ;
[\n] { return 0; }
. { return yytext[0]; }
%%

Yacc File :

%{
#include <stdio.h>
%}

%token NUM
%left '-''+'
%right '*' '/'

%%

start : exp { printf("%d\n", $$); };

exp : exp '+' exp { $$ = $1 + $3; }


| exp '-' exp { $$ = $1 - $3; }
| exp '*' exp { $$ = $1 * $3; }
| exp '/' exp
{
if ($3 == 0)
yyerror("error");
else
$$ = $1 / $3;
}
| '(' exp ')' { $$ = $2; }
| NUM { $$ = $1; }
;

%%

main()
{
printf("Enter the Expr. in terms of integers\n");
if (yyparse() == 0)
{
printf("Success\n");
18

getch();
}
}

yywrap() {}

yyerror()
{
printf("Error\n");
}

Output-7:
19

8. program for implementing type checking for given expression.

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define SIZE 128
#define NONE -1
#define EOS '\0'
#define NUM 257
#define KEYWORD 258
#define ID 259
#define DONE 260
#define MAX 999
char lexemes[MAX];
char buffer[SIZE];
int lastchar=-1;
int lastentry=0;
int tokenval=DONE;
int lineno=1;
int lookahead;
struct entry
{
char *lexptr;
int token;
}
symtable[100];
struct entry
keywords[]= {"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",KEYWORD,
"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWORD,0,0
};
void Error_Message(char *m)
{
fprintf(stderr,"line %d, %s \n",lineno,m);
exit(1);
}
int look_up(char s[ ])
{
int k;
for(k=lastentry; k>0; k--)
if(strcmp(symtable[k].lexptr,s)==0)
return k;
return 0;
}
int insert(char s[ ],int tok)
{
int len;
len=strlen(s);
if(lastentry+1>=MAX)
Error_Message("Symbpl table is full");
if(lastchar+len+1>=MAX)
Error_Message("Lexemes array is full");
lastentry=lastentry+1;
symtable[lastentry].token=tok;
symtable[lastentry].lexptr=&lexemes[lastchar+1];
lastchar=lastchar+len+1;
strcpy(symtable[lastentry].lexptr,s);
return lastentry;
}
/*void Initialize()
{
20

struct entry *ptr;


for(ptr=keywords;ptr->token;ptr+1)
insert(ptr->lexptr,ptr->token);
}*/
int lexer()
{
int t;
int val,i=0;
while(1)
{
t=getchar();
if(t==' '||t=='\t');
else if(t=='\n')
lineno=lineno+1;
else if(isdigit(t))
{
ungetc(t,stdin);
scanf("%d",&tokenval);
return NUM;
}
else if(isalpha(t))
{
while(isalnum(t))
{
buffer[i]=t;
t=getchar();
i=i+1;
if(i>=SIZE)
Error_Message("Compiler error");
}
buffer[i]=EOS;
if(t!=EOF)
ungetc(t,stdin);
val=look_up(buffer);
if(val==0)
val=insert(buffer,ID);
tokenval=val;
return symtable[val].token;
}
else if(t==EOF)
return DONE;
else
{
tokenval=NONE;
return t;
}
}
}
void Match(int t)
{
if(lookahead==t)
lookahead=lexer();
else
Error_Message("Syntax error");
}
void display(int t,int tval)
{
if(t=='+'||t=='-'||t=='*'||t=='/')
printf("\nArithmetic Operator: %c",t);
else if(t==NUM)
printf("\n Number: %d",tval);
else if(t==ID)
21

printf("\n Identifier: %s",symtable[tval].lexptr);


else
printf("\n Token %d tokenval %d",t,tokenval);
}
void F()
{
//void E();
switch(lookahead)
{
case '(' :
Match('(');
E();
Match(')');
break;
case NUM :
display(NUM,tokenval);
Match(NUM);
break;
case ID :
display(ID,tokenval);
Match(ID);
break;
default :
Error_Message("Syntax error");
}
}
void T()
{
int t;
F();
while(1)
{
switch(lookahead)
{
case '*' :
t=lookahead;
Match(lookahead);
F();
display(t,NONE);
continue;
case '/' :
t=lookahead;
Match(lookahead);
display(t,NONE);
continue;
default :
return;
}
}
}
void E()
{
int t;
T();
while(1)
{
switch(lookahead)
{
case '+' :
t=lookahead;
Match(lookahead);
T();
22

display(t,NONE);
continue;
case '-' :
t=lookahead;
Match(lookahead);
T();
display(t,NONE);
continue;
default :
return;
}
}
}
void parser()
{
lookahead=lexer();
while(lookahead!=DONE)
{
E();
Match(';');
}
}
main()
{
char ans[10];
printf("Enter the expression,at last;and press ctrl-z to terminate\n");
parser();
return 0;
}

Output-8:
23

9. program to convert the BNF rules into YACC.

Lex File:

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

%%

Yacc File:

%{
#include<string.h>
#include<stdio.h>
24

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);
25

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 {
26

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

%%

void push(int data) {


stk.top++;
if (stk.top == 100) {
printf("\n Stack overflow\n");
exit(1);
}
stk.items[stk.top] = data;
}

int pop() {
int data;
if (stk.top == -1) {
printf("\n Stack underflow\n");
exit(1);
}
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);
}
27

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

Input.txt:

int a=10, b=20, c;


c = a + b;

Output-9:
28

10. program to implement data flow and control flow analysis.

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>

struct stack {
int no;
struct stack *next;
} *start = NULL;

typedef struct stack st;

void push();
int pop();
void display();

void main() {
char ch;
int choice, item;
do {
printf("\n 1: push");
printf("\n 2: pop");
printf("\n 3: display");
printf("\n Enter your choice:");
scanf("%d", &choice);

switch (choice) {
case 1:
push();
break;
case 2:
item = pop();
printf("The delete element is %d", item);
break;
case 3:
display();
break;
default:
printf("\n Wrong choice");
};

printf("\n Do you want to continue(Y/N)");


fflush(stdin);
scanf("%c", &ch);
} while (ch == 'Y' || ch == 'y');
}

void push() {
st *node;
node = (st *)malloc(sizeof(st));
printf("\n Enter the number to be insert");
scanf("%d", &node->no);
node->next = start;
start = node;
}

int pop() {
st *temp;
temp = start;
if (start == NULL) {
29

printf("Stack is already empty");


getch();
exit(0);
} else {
start = start->next;
free(temp);
}
return (temp->no);
}

void display() {
st *temp;
temp = start;
while (temp->next != NULL) {
printf("\nno = %d", temp->no);
temp = temp->next;
}
printf("\nno = %d", temp->no);
}

Output-10:
30

11. program to implement stack storage allocation strategies.

#define Bool int


#define True 1
#define False 0
#include <stdio.h>
#include <conio.h>
#define MaxSize 10

int S[MaxSize];
int Top = -1;

Bool IsEmpty() {
return Top == -1;
}

Bool IsFull() {
return Top == MaxSize - 1;
}

void Push(int ele) {


if (IsFull())
printf("Stack is Full.");
else
S[++Top] = ele;
}

int Pop() {
if (IsEmpty()) {
printf("Stack is Empty.");
return -1;
} else {
return S[Top--];
}
}

int TopEle() {

if (IsEmpty()) {
printf("Stack is Empty.");
return -1;
}
return S[Top];
}

void Display() {
int i;
if (IsEmpty())
printf("Stack is Empty.");
else {
printf("Stack is ...\n");
for (i = Top; i >= 0; i--)
printf("%d\n", S[i]);
}
}

int main() {
int ch, ele;
do {
//clrscr();
printf("Stack Operation Menu\n");
printf("--------------------\n\n");
31

printf("1.Push\n2.Pop\n3.Display\n4.Exit\n\n");
printf("Enter Your Choice [1..4] : ");
scanf("%d", &ch);

switch (ch) {
case 1:
printf("Enter the Element : ");
scanf("%d", &ele);
Push(ele);
break;
case 2:
ele = Pop();
if (ele != -1)
printf("%d is deleted.\n", ele);
break;
case 3:
Display();
break;
case 4:
break;
default:
printf("Invalid Choice, Try Again.\n");
getch();
}
getch();
} while (ch != 4);
}

Output-11:
32

12. program to implement heap storage allocation strategies.

#define bool int


#define True 1
#define False 0
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

typedef struct node Node;


struct node
{
int data;
Node *next;
};

Node *Top = NULL;

bool IsEmpty()
{
return Top == NULL;
}

bool IsFull()
{
return False;
}

void Push(int ele)


{
Node *p;
if (IsFull())
printf("Stack is Full.");
else
{
p = (Node *)malloc(sizeof(Node));
p->data = ele;
p->next = Top;
Top = p;
}
}

int Pop()
{
Node *p;
int ele;
if (IsEmpty())
{
printf("Stack is Empty.");
return -1;
}
else
{
ele = Top->data;
p = Top;
Top = Top->next;
free(p);
return ele;
}
}
33

int TopEle()
{
return Top->data;
}

void Display()
{
Node *p;
if (IsEmpty())
printf("Stack is Empty.");
else
{
printf("Stack is ...\n");
for (p = Top; p != NULL; p = p->next)
printf("--->%d\n", p->data);
}
}

int main()
{
int ch, ele;
do
{
//clrscr();
printf("Stack Operation Menu\n");
printf("--------------------\n\n");
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n\n");
printf("Enter Your Choice [1..4] : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter the Element : ");
scanf("%d", &ele);
Push(ele);
break;
case 2:
ele = Pop();
if (ele != -1)
printf("%d is deleted.\n", ele);
break;
case 3:
Display();
break;
case 4:
break;
default:
printf("Invalid Choice, Try Again.\n");
getch();
}
getch();
} while (ch != 4);
}
34

Output-12:
35

13. program to construct a directed acyclic graph (DAG).

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define size 20

typedef struct node


{
char data;
struct node *left;
struct node *right;
} btree;

btree *stack[size];
int top;

int main()
{
btree *root;
char exp[80];
btree *create(char exp[80]);
void dag(btree *root);
// clrscr();
printf("\nEnter the postfix expression:\n");
scanf("%s", exp);
top = -1;
root = create(exp);
printf("\nThe tree is created.....\n");
printf("\nInorder DAG is : \n\n");
dag(root);
getchar();
}

btree *create(char exp[])


{
btree *temp;
int pos;
char ch;
void push(btree*);
btree *pop();
pos = 0;
ch = exp[pos];
while (ch != '\0')
{
temp = ((btree*)malloc(sizeof(btree)));
temp->left = temp->right = NULL;
temp->data = ch;

if (isalpha(ch))
push(temp);
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
temp->right = pop();
temp->left = pop();
push(temp);
}
else
printf("\n Invalid char Expression\n");

pos++;
ch = exp[pos];
36

}
temp = pop();
return(temp);
}

void push(btree *Node)


{
if (top + 1 >= size)
printf("Error: Stack is full\n");
top++;
stack[top] = Node;
}

btree* pop()
{
btree *Node;
if (top == -1)
printf("\nError: stack is empty..\n");
Node = stack[top];
top--;
return(Node);
}

void dag(btree *root)


{
btree *temp;
temp = root;
if (temp != NULL)
{
dag(temp->left);
printf("%c", temp->data);
dag(temp->right);
}
}

Output-13:
37

14. program to implement the back end of the compiler.

#include<stdio.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>

int main()
{
char icode[10][30], str[20], opr[10];
int i = 0;
//clrscr();
printf("Enter the set of intermediate code (terminated by exit):\n");

do
{
scanf("%s", icode[i]);
}
while (strcmp(icode[i++], "exit") != 0);

printf("Target Code Generation\n");


printf("----------------------\n");
i = 0;
do
{
strcpy(str, icode[i]);
switch (str[3])
{
case '+': strcpy(opr, "ADD"); break;
case '-': strcpy(opr, "SUB"); break;
case '*': strcpy(opr, "MUL"); break;
case '/': strcpy(opr, "DIV"); break;
}

printf("\n\tMOV\t%c, R%d", str[2], i);


printf("\n\t%s\t%c,R%d", opr, str[4], i);
printf("\n\tMOV\tR%d, %c", i, str[0]);
}
while (strcmp(icode[++i], "exit") != 0);

getch();
}

Output-14:
38

15. program to implement simple code optimization technique.

#include<stdio.h>
#include<conio.h>
#include<string.h>

char s[20], o[20];

int main()
{
int i = 0, j = 0, k, f1 = 1, f = 1, k1 = 0;
void part();
//clrscr();
printf("\n Enter the input string\n");
scanf("%s", o);
strlen(o);

while (o[k1] != '\0')


{
if ((o[k1] == '=') == 1)
{
break;
}
k1++;
}

for (j = k1 + 1; j < strlen(o); j++)


{
s[i] = o[j];
i++;
}
s[i] = '\0';
i = strlen(s);
j = 0;
printf("\n Three address code is\n");

if (i > 3)
{
while (s[j] != '\0')
{
if ((s[j] == '*') == 1 || (s[j] == '/') == 1)
{
k = j;
if (f1 != 0)
{
printf("t1=%c\n", s[k + 1]);
printf("t2=%c%ct1", s[k - 1], s[k]);
}
else
{
if (k > 3)
{
printf("t2=t1%c%c\n", s[k], s[k + 1]);
}
else
{
printf("\t2=t1%c%c\n", s[k], s[k - 1]);
}
}
f = 0;
break;
}
39

j++;
}

j = 0;
while (s[j] != '\0')
{
if ((s[j] == '+') == 1 || (s[j] == '-') == 1)
{
k = j;
if (f == 0)
{
if (k < 3)
{
printf("\nt3=t2%c%c\n", s[k], s[k - 1]);
}
else
{
printf("\nt3=t2%c%c\n", s[k], s[k + 1]);
}
}
else
{
printf("t1=%c%c%c\n", s[k - 1], s[k], s[k + 1]);
}
f1 = 0;
}
j++;
}
printf("%c=t3", o[0]);
}
else
{
printf("t1=%s\n", s);
printf("%c=t1", o[0]);
}
part();
getch();
}

void part()
{
int i = 0, j = 0, k, f1 = 1, f = 1, k1 = 0;
while (o[k1] != '\0')
{
if ((o[k1] == '=') == 1)
{
break;
}
k1++;
}

for (j = k1 + 1; j < strlen(o); j++)


{
s[i] = o[j];
i++;
}
s[i] = '\0';
i = strlen(s);
j = 0;
printf("\n OPTIMIZED CODE\n");

if (i > 3)
{
40

while (s[j] != '\0')


{
if ((s[j] == '*') == 1 || (s[j] == '/') == 1)
{
k = j;
if (f1 != 0)
{
printf("t1=%c%c%c\n", s[k - 1], s[k], s[k + 1]);
}
else
{
if (k > 3)
{
printf("t2=t1%c%c\n", s[k], s[k + 1]);
}
else
{
printf("\t2=t1%c%c\n", s[k], s[k - 1]);
}
}
f = 0;
break;
}
j++;
}

j = 0;
while (s[j] != '\0')
{
if ((s[j] == '+') == 1 || (s[j] == '-') == 1)
{
k = j;
if (f == 0)
{
if (k < 3)
{
printf("t2=t1%c%c\n", s[k], s[k - 1]);
}
else
{
printf("t2=t1%c%c\n", s[k], s[k + 1]);
}
}
else
{
printf("t1=%c%c%c\n", s[k - 1], s[k], s[k + 1]);
}
f1 = 0;
}
j++;
}
printf("%c=t2", o[0]);
}
else
{
printf("t1=%s\n", s);
printf("%c=t1", o[0]);
}
}
41

Output-15:
42

16. program to implement simple code optimization technique using do-while.

Before using for loop:

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
int i, n;
int fact = 1;

cout << "\nEnter a number: ";


cin >> n;

for (i = n; i >= 1; i--) {


fact = fact * i;
}

cout << "The factorial value is: " << fact << endl;

return 0;
}

After using for loop:

#include<iostream.h>
#include<conio.h>
void main() {
clrscr();
int n, f;
f = 1;
printf("Enter the number:\n");
scanf("%d", &n);
do {
f = f * n;
n--;
} while(n > 0);
printf("The factorial value is: %d", f);
getch();
}

Output:

Using for loop:


43

Using do-while loop:

You might also like