You are on page 1of 46

Ex.

No: 1

SYMBOL TABLE IMPLEMENTATION

Date:
AIM:
To write a C program to implement a symbol table.

ALGORITHM:
1) Start the program.
2) Get the input from the user with the terminating symbol $.
3) Allocate memory for the variable by dynamic memory allocation function.
4) If the next character of the symbol is an operator then only the memory is allocated.
5) While reading, the input symbol is inserted into symbol table along with its memory address.
6) The steps are repeated till $ is reached.
7) To reach a variable, enter the variable to the searched and symbol table has been checked for
corresponding variable, the variable along with its address is displayed as result.
8) Stop the program.

PROGRAM CODING:

#include <stdio.h>
#include<conio.h>
#include<ctype.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n,flag=0;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $ : ");
while((c=getchar())!='$')
{
b[i]=c;
N.Senthil Murugan AP/CSE

i++;
}
n=i-1;
printf("Given Expression : ");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol\taddr\ttype");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
if(j==n)
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("%c\t%d\tidentifier",c,p);
}
else
{
ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c\t%d\tidentifier\n",c,p);
x++;
}}}
j++;
}
printf("\nThe symbol is to be searched");
srch=getch();
for(i=0;i<=x;i++)
N.Senthil Murugan AP/CSE

{
if(srch==d[i])
{
printf("\nSymbol Found");
printf("\n%c%s%d\n",srch," @address ",add[i]);
flag=1;
}
}
if(flag==0)
printf("\nSymbol Not Found");
getch();
}
OUTPUT:

RESULT:
Thus the above the program is executed and the required output is obtained.

N.Senthil Murugan AP/CSE

Ex.No :2
IMPLEMENTATION OF LEXICAL ANALYSIS IN C
Date:

AIM:
To write a C Program to implement a Lexical analyzer.

ALGORITHM:
1) Start the program.
2) Declare all the variables and file pointers.
3) Display the input program.
4) Separate the keyword in the program and display it.
5) Display the header files of the input program.
6) Separate the operators of the input program and display it.
7) Print the punctuation marks.
8) Print the constant that are present in input program.
9) Print the identifiers of the input program.
10) Stop the program.

PROGRAM CODING:
#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[32][10]={"auto","break","case","char","const","continu
e","default",
"do","double","else","enum","extern","float","for","goto",
"if","int","long","register","return","short","signed",
N.Senthil Murugan AP/CSE

"sizeof","static","struct","switch","typedef","union",
"unsigned","void","volatile","while"};
main()
{
char ch,str[25],seps[15]="
\t\n,;(){}[]#\"<>",oper[]="!%^&*-+=~|.<>/?";
int j;
char fname[50];
FILE *f1;
//clrscr();
printf("enter file path (drive:\\fold\\filename)\n");
scanf("%s",fname);
f1 = fopen(fname,"r");
//f1 = fopen("Input","r");
if(f1==NULL)
{
goto END;
}
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++)
{
N.Senthil Murugan AP/CSE

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");
i=-1;
break;
}
str[i]='\0';
keyw(str);
}
}
if(i!=-1)
{
N.Senthil Murugan AP/CSE

str[i]=ch;
i++;
}
else
i=0;
}
printf("Keywords: %d\nIdentifiers: %d\nOperators:
%d\nNumbers: %d\n",kw,id,op,num);
//getch();
END:
printf("file not found");
}
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++;
}
N.Senthil Murugan AP/CSE

else
{
//if(p[0]!=13&&p[0]!=10)
if(p[0]!='\0')
{
printf("%s is an identifier\n",p);
id++;
}
}
}
i=-1;
}

INPUT: (INPUT.C)
#include<stdio.h>
#include<conio.h>
void main()
{
Int a,b,c;
a=10;
b=5;
c=a+b;
printf(The sum is %d,c);
getch();
}

N.Senthil Murugan AP/CSE

OUTPUT:

RESULT:
Thus the above the program is executed and the required output is obtained.

N.Senthil Murugan AP/CSE

Ex. No: 3

IMPLEMENTATION OF LEXICAL ANALYSER USING


LEX TOOL

Date:

AIM:
To write a lex program to implement the lexical analyzer.

ALGORITHM:
1. Start the program
2. Open a file file.c in read and include the yylex() tool for input scanning.
3. Define the alphabets and numbers.
4. Print the preprocessor, function, keyword using yytext.lex tool.
5. Print the relational, assignment and all the operator using yytext() tool.
6. Also scan and print where the loop ends and begins.
7. Use yywrap() to enter an error.
8. Stop the program.

PROGRAM CODING:
%{
int COMMENT=0;
%}
identifier [_a-zA-Z][_a-zA-Z0-9]*
%%
#.* {printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}
int |
double |
N.Senthil Murugan AP/CSE

float |
char |
while |
for |
do |
if |
break |
continue |
void |
switch |
case |
long |
struct |
const |
typedef |
return |
else |
goto {printf("\n\t%s is a KEYWORD",yytext);}
"/*" {COMMENT=1;
printf("\n\n\t COMMENT ENDS\n");}
{identifier}\( {if(!COMMENT)
printf("\n\t %s ) is a FUNCTION \n",yytext);}
\{

{if(!COMMENT) printf("\n\t BLOCK BEGINS");}

\}

{if(!COMMENT) printf("\n\t BLOCK ENDS");}

{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n\t %s


IDENTIFIER",yytext);}
\".*\"

{if(!COMMENT) printf("\n\t %s is a STRING",yytext);}

[0-9]+

{if(!COMMENT) printf("\n\t %s is a NUMBER",yytext);}


N.Senthil Murugan AP/CSE

\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;


\(

printf("\n");}

ECHO;

= {if(!COMMENT) printf("\n\t%s is an ASSIGNMENT


OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL
OPERATOR",yytext);}
\+|\-|\*|\%|\/ {if(!COMMENT) printf("\n\t%s is a ARITHMETIC
OPERATOR",yytext);}
%%
int main(int argc,char **argv)
{
if(argc > 1)
{
FILE *file;
file=fopen(argv[1],"r");
if(!file)
{
printf("could not open %s\n",argv[1]);
exit(0);
}
yyin=file;
}
yylex();
printf("\n\n");
return 0;
N.Senthil Murugan AP/CSE

}
int yywrap()
{
return 0;
}

INPUT (area.c):
#include<stdio.h>
#include<stdlib.h>
double area_of_circle(double r);
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("usage: %s radius\n",argv[0]);
{
exit(1);
}
else {
double radius=atof(argv[1]);
double area=area_of_circle(radius);
printf("Area of circle with radius %f=%f\n",radius,area);
}
return 0;
}

N.Senthil Murugan AP/CSE

OUTPUT:

RESULT:
Thus the above the program is executed and the required output is obtained.

N.Senthil Murugan AP/CSE

Ex. No: 4a

YACC PROGRAM TO RECOGNIZE A VALID

Date:

ARITHMETIC EXPRESSION

AIM:
ALGORITHM:
PROGRAM CODING:
%{ /* validate simple arithmetic expression */
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#define YYSTYPE double
%}
%token num
%left '+' '-'
%left '*' '/'
%%
st: st expr '\n' {printf("Valid");}
|st '\n'
|
|error '\n' {printf("INVALID");}
;
expr: num
|expr '+' expr
|expr '/' expr
%%
main()
{
printf(" ENTER AN EXPRESSION TO VALIDATE");
yyparse();
}
yylex()
{
int ch;
while((ch=getchar())==' ');
if(isdigit(ch)|ch=='.')
{
ungetc(ch,stdin);
scanf("%lf",&yylval);
return num;
N.Senthil Murugan AP/CSE

}
return ch;
}
yyerror(char *s)
{
printf("%S",s);
}
OUTPUT:
C:\Flex Windows\EditPlusPortable>yacc -d arithval.y
C:\Flex Windows\EditPlusPortable>cc y.tab.c -ll
C:\Flex Windows\EditPlusPortable>./a.out

ENTER AN EXPRESSION TO VALIDATE5+9


Valid
4+6
Valid
5INVALID

RESULT:
Thus the above the program is executed and the required output is obtained.

N.Senthil Murugan AP/CSE

Ex. No: 4b
YACC PROGRAM TO RECOGNIZE A VALID VARIABLE
Date:

AIM:
ALGORITHM:
PROGRAM CODING:

%{ /* Y prg to recognize valid variable, which starts with a


letter,
followed by any number of letters or digits. */
#include<stdio.h>
#include<ctype.h>
%}
%token let dig
%%
sad: let recld '\n' {printf("accepted\n"); return 0;}
| let '\n' {printf("accepted\n"); return 0;}
|
|error {yyerror("rejected\n");return 0;}
;
recld: let recld
| dig recld
| let
| dig
;
%%
yylex()
{
char ch;
while((ch=getchar())==' ');
if(isalpha(ch))
return let;
if(isdigit(ch))
return dig;
return ch;
}
yyerror(char *s)
{
printf("%s",s);
}
N.Senthil Murugan AP/CSE

main()
{
printf("ENTER A variable : ");
yyparse();
}

Output:
C:\Flex Windows\EditPlusPortable>yacc -d vvar.y
C:\Flex Windows\EditPlusPortable>cc y.tab.c -ll
C:\Flex Windows\EditPlusPortable>./a.out
ENTER A variable : a45
accepted
C:\Flex Windows\EditPlusPortable>./a.out
ENTER A variable : 5e
syntax errorrejected
C:\Flex Windows\EditPlusPortable>./a.out
ENTER A variable : ab
accepted

RESULT:
Thus the above the program is executed and the required output is obtained.

N.Senthil Murugan AP/CSE

Ex. No: 4c

IMPLEMENTATION OF CALCULATION USING LEX

Date:

AND YACC

AIM:
To write a program to implement calculator using lex and yacc.

ALGORITHM:
1. Start the program.
2. Perform the calculation using both the lex and yacc.
3. In the lex tool, if the given expression contains numbers and letters then they are
displayed.
4. In the same way, the digits, letters and uminus are identified and displayed using yacc
tool.
5. The calculation is performed and the result is displayed.
6. Stop the program.

PROGRAM CODING:
USING LEX TOOL:
%{
#include <stdio.h>
#include "y.tab.h"
int c;
extern int yylval;
%}
%%
" "
;
[a-z]
{
c = yytext[0];
N.Senthil Murugan AP/CSE

yylval = c - 'a';
return(LETTER);
[0-9]

}
{
c = yytext[0];
yylval = c - '0';
return(DIGIT);

}
[^a-z0-9\b]

{
c = yytext[0];
return(c);
}

%%

USING YACC TOOL:


%{
#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;
}
;
N.Senthil Murugan AP/CSE

expr:

'(' expr ')'


{
$$ = $2;
}
|
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 '|' expr
{
$$ = $1 | $3;
}
|
'-' expr %prec UMINUS
{
$$ = -$2;
}
|
LETTER
{
N.Senthil Murugan AP/CSE

number:

$$ =
}
|
number
;
DIGIT
{
$$ =
base
}
number
{
$$ =
}
;

regs[$1];

$1;
= ($1==0) ? 8 : 10;
|
DIGIT
base * $1 + $2;

%%
main()
{
return(yyparse());
}
yyerror(s)
char *s;
{
fprintf(stderr, "%s\n",s);
}
yywrap()
{
return(1);
}

OUTPUT:

N.Senthil Murugan AP/CSE

RESULT:
Thus the above the program is executed and the required output is obtained.

Ex. No: 5

Convert the BNF rules into Yacc form and write


code to generate Abstract Syntax Tree.

Date:

AIM:
ALGORITHM:
PROGRAM CODING:
LEX
%{
#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;}
N.Senthil Murugan AP/CSE

\< |
\> |
\>= |
\<= |
== {strcpy(yylval.var,yytext);
return RELOP;}
[ \t] ;
\n LineNo++;
. return yytext[0];
%%
int yywrap() {
return 1;
}
YACC
%{
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
void push(int);
void AddQuadruple(char *,char *,char *,char *);
struct quad
{
char op[5];
char arg1[10];
char arg2[10];
char result[10];
}QUAD[30];
struct stack
{
int items[100];
int top;
}stk;
N.Senthil Murugan AP/CSE

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{
N.Senthil Murugan AP/CSE

strcpy(QUAD[Index].op,"=");
strcpy(QUAD[Index].arg1,$3);
strcpy(QUAD[Index].arg2,"");
strcpy(QUAD[Index].result,$1);
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++;
}
N.Senthil Murugan AP/CSE

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{
Ind=pop();
sprintf(QUAD[Ind].result,"%d",StNo);
Ind=pop();
sprintf(QUAD[Ind].result,"%d",Index);
}
;
WHILELOOP: WHILE '(' CONDITION ')' {
N.Senthil Murugan AP/CSE

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++;
}
;
%%
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");
exit(0);
}
yyin=fp;
}
N.Senthil Murugan AP/CSE

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].resu
lt);
}
printf("\n\t\t-------------------------------------");
printf("\n\n");
return 0;
}
void push(int data)
{
stk.top++;
if(stk.top==100)
{
printf("\n Stack overflow\n");
exit(0);
}
stk.items[stk.top]=data;
}
int pop()
{
int data;
if(stk.top==-1)
{
printf("\n Stack underflow\n");
exit(0);
}
N.Senthil Murugan AP/CSE

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);
}
INPUT: ( bnf.txt)
main()
{
int a,b,c;
if(a<b)
{
a=a+b;
}
while(a<b)
{
a=a+b;
}
if(a<=b)
{
c=a-b;
}
else
{
c=a+b;
}
}

N.Senthil Murugan AP/CSE

OUTPUT:

RESULT:

Ex. No: 8

IMPLEMENTATION OF STORAGE ALLOCATION


STRATEGY

Date:

AIM:
ALGORITHM:
PROGRAM CODING:
#include"stdio.h"
#include"conio.h"
#include"stdlib.h"
#define TRUE 1
#define FALSE 0
typedef struct Heap
{
int data;
N.Senthil Murugan AP/CSE

struct Heap *next;


}node;
node *create();
void main()
{
/*local declarations*/
int choice,val;
char ans;
node *head;
void display(node *);
node *search(node *,int);
node *insert(node *);
void dele(node **);
head=NULL;
do
{
clrscr();
printf(\n Program to perform various operations on heap
using dynamic memory management);
printf (\n1.Create):
printf (\n2.Display):
printf (\n3.Insert an element in a list);
printf (\n4.Delete an element from list);
printf (\n5.Quit);
printf (\n Enter Your Choice(1-5));
scanf(%d,&choice);
switch(choice)
{
case 1:head=create();
break;
case 2:display(head);
break;
case 3:head=insert(head);
break;
case 4:dele(&head);
break;
case 5:exit(0);
default:clrscr();
printf(Invalid Choice,Try again);
getch();
}
}while(choice!=5);
}
/*The create function creates a list of allocated node
*Input:None
*Output:Retyurns a pointer to head of list
N.Senthil Murugan AP/CSE

*Parameter Passing Methopd:Node


**/
node *create()
{
node *temp,*new,* head;
int val,flag;
char ans=y;
node *get_node();
temp=NULL;
flag=TRUE;
/*flag to indicate whether a new node is created for the
first time or not*/
do
{
printf(\n Enter the Element);
scanf(%d,&val);
/*allocate new node*/
new =get_node();
if(new==NULL)
printf(\n Memory is not allocated);
new-> data=val;
if (flag==TRUE)/* Executed only for the first time*/
{
head=new;
temp=head; /*head is the first node in the heap*/
flag=FALSE;
}
else
{
/*temp keeps track of the most recently created node*/
temp->next=new;
temp=new;
}
printf(\nDo you want to enter more elements?(y/n));
ans=getch();
}while(ans= = y);
printf(\nThe list is created);
getch();
clrscr();
return head;
}
node *get_node()
N.Senthil Murugan AP/CSE

{
node *temp;
temp=(node*)malloc(sizeof(node));
//using the mem. Allocation function
temp->next=NULL;
return temp;
}
void display(node*head)
{
node *temp;
temp=head;
if(temp= =NULL)
{
printf(\n The list is empty\n);
getch();
clrscr();
return;
}
while(temp!= NULL)
{
printf(%d->,temp-> data);
temp=temp->next;
}
print(NULL);
getch();
clrscr();
}
node *search(node *head,int key)
{
node*temp;
int found;
temp=head;
if (temp= =Null)
{
printf(The linked list is empty\n);
getch();
clrscr();
return NULL;
}
found=FALSE;
While(temp!= NULL && found= =FALSE)
{
if(temp->data != key)
temp = temp->next;
else
found = True;
N.Senthil Murugan AP/CSE

}
if(found == TRUE)
{
printf(\n The Elements is present in the list\n);
getch();
return temp;
}
else
printf(\n The Element is not present in the list\n);
getch();
return NULL;
}
node *insert(node *head)
{
int choice;
node *insert_head(node*);
void insert_after(node*);
void insert_last(node*);
printf(\n1.Insert a node as a head node);
printf(\n1.Insert a node as a last node);
printf(\n1.Insert a node as at the intermediate position
in the list );
printf(\n1.Enter your choice for insertion of node );
scanf(%d,&choice);
switch(choice)
{
case 1:head = insert_head(head);
break;
case2:insert_last(head);
break;
case2:insert_after (head);
break;
}
return head;
}
/*Insertion of node at first position*/
node *insert_head(node*head)
{
node *New,*temp;
New = get_node();
printf (\n Enter the element which you want to insert );
scanf(%d,&New->data);
if(head == NULL)
head = New;
N.Senthil Murugan AP/CSE

else
{
temp=head;
New->next = temp;
head= New;
}
return head;
}
/*Insertion of node at last position*/
void insert_last(node *head)
{
node *New,*temp;
New = get_node();
printf (\n Enter the element which you want to insert );
scanf(%d,&New->data);
if(head == NULL)
{
head = New;
}
else
{
temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=New;
New->next=NULL;
}
}
/*Insertion of node at intermediate position*/
void insert_after(node *head)
{
int key;
node *New,*temp;
New = get_node();
printf(Enter the element after which you want to insert
);
scanf(%d,&key);
temp=head;
do
{
if(temp->data==key)
{
printf (Enter element which you want to insert );
scanf(%d,&New->data);
New->next=temp->next;
N.Senthil Murugan AP/CSE

temp->next=New;
return;
}
else
temp=temp->next;
}while(temp!=NULL);
}
node *get_prev(node *head,int val)
{
node*temp.*prev;
int flag;
temp = head;
if(temp == NULL)
return NULL;
flag = FALSE;
prev = NULL;
while(temp!=NULL && !flag)
{
if(temp->data!=val)
{
prev = temp;
temp = temp->next;
}
else
flag = TRUE;
}
if(flag) /*if Flag is true*/
return prev;
else
return NULL;
}
void dele(node **head)
{
int key;
node *New,*temp;
temp=*head;
if (temp== NULL)
{
printf (\n The list is empty\n );
getch();
clrscr();
return;
}
clrscr();
N.Senthil Murugan AP/CSE

printf("\nENTER the Element you want to delete:");


scanf("%d".&key);
temp= search(*head,key);
if(temp !=NULL)
{
prev = get_prev(*head,key);
if(prev != NULL)
{
prev ->next = temp-> next;
free(temp);
}
else
{
*head = temp->next;
free(temp); // using the mem. Dellocation function
}
printf(\nThe Element is deleted\n);
getch();
clrscr();
}
OUTPUT:
Program to perform various operations on heap using Dynamic memory management.
1. Create
2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 1
Enter the element: 10
Do you want to enter more elements? (y/n)y
Enter the element:20
Do you want to enter more elements?(y/n)y
Enter the element:30
Do you want to enter more elements?(y/n)n
The List is created
Program to perform various operations on Heap using Dynamic memory management.
1. Create
N.Senthil Murugan AP/CSE

2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 4
Enter the element you want to delete: 20
The element is present in the list
The element is deleted
Program to perform various operations on Heap using Dynamic memory management.
1. Create
2. Display
3. Insert an element in a list
4. Delete an element from list
5. Quit
Enter your choice(1-5) 2
10-> 30-> NULL

N.Senthil Murugan AP/CSE

RESULT:
Thus the above the program is executed and the required output is obtained.

Ex. No: 10
IMPLEMENTATION OF BACK END OF COMPILER
Date:

AIM:
To write a C program to implement the back end of the compiler.

ALGORITHM:

1) Start the program.


2) Get the three variables from statements and stored in the text file k.txt.
3) Compile the program and give the path of the source file.
4) Execute the program.
5) Target code for the given statement was produced.
6) Stop the program.

N.Senthil Murugan AP/CSE

PROGRAM CODING:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<stdlib.h>
void main(){
int i=2,j=0,k=2,k1=0;
char ip[10],kk[10];
FILE *fp;
printf("\nEnter the filename of the intermediate code");
scanf("%s",&kk);
fp=fopen(kk,"r");
if(fp==NULL){
printf("\nError in Opening the file");
getch();
}
while(!feof(fp)){
fscanf(fp,"%s\n",ip);
printf("\t\t%s\n",ip);
}
rewind(fp);
printf("\n----------------------------------------\n");
printf("\tStatement \t target code\n");
printf("\n----------------------------------------\n");
while(!feof(fp))
{
fscanf(fp,"%s",ip);
printf("\t%s",ip);
printf("\t\tMOV %c,R%d\n\t",ip[i+k],j);
if(ip[i+1]=='+')
printf("\t\tADD ");
else
printf("\t\tSUB ");
if(islower(ip[i]))
printf("%c,R%d\n\n",ip[i+k1],j);
else
printf("%c,%c\n",ip[i],ip[i+2]);
j++;
k1=2;
k=0;
}
printf("\n----------------------------------------\n");
getch();
fclose(fp);
}

INPUT: (k.txt)
X=a-b
Y=a-c
Z=A+B
C=A-B
N.Senthil Murugan AP/CSE

OUTPUT:

RESULT:
Thus the above the program is executed and the required output is obtained.

Ex. No: 11
Date:

IMPLEMENTATION OF CODE OPTIMIZATION TECHNIQUES

AIM:

To write a program for implementation of Code Optimization Technique in C.

.co
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<stdlib.h>
N.Senthil Murugan AP/CSE

#include<ctype.h>
struct ConstFold
{
char new_str[10];
char str[10];
}opt_Data[20];
void ReadInput(char Buffer[],FILE *Out_file);
int Gen_token(char str[],char Tokens[][10]);
int New_Index=0;
int main()
{
FILE *In_file,*Out_file;
char Buffer[100],ch;
int i=0;
In_file = fopen("code.txt","r");
Out_file = fopen("output.txt","w");
while(1)
{
ch = fgetc(In_file);
i=0;
while(1)
{
if(ch == '\n')
break;
Buffer[i++]=ch;
ch = fgetc(In_file);
if(ch == EOF)
break;
}//End while
if(ch ==EOF)
break;
Buffer[i]='\0';
ReadInput(Buffer, Out_file);//writing to the output file
}//End while
return 0;
}//End main
void ReadInput(char Buffer[],FILE *Out_file)
{
char temp[100],Token[10][10];
int n,i,j,flag=0;
strcpy(temp,Buffer);
n= Gen_token(temp,Token);
for(i=0;i<n;i++)
{
if(!strcmp(Token[i],"="))
{
if(isdigit(Token[i+1][0])||Token[i+1][0] == '.')
N.Senthil Murugan AP/CSE

{
/*If yes then saving that number and its variable
In the Opt_Data array*/
flag=1;
strcpy(opt_Data[New_Index].new_str,Token[i-1]);
strcpy(opt_Data[New_Index++].str,Token[i+1]);
}//End if
}//End if
}//End for
if(!flag)
{
for(i=0;i<New_Index;i++)
{
for(j=0;j<n;j++)
{
if(!strcmp(opt_Data[i].new_str,Token[j]))
strcpy(Token[j],opt_Data[i].str);
}//End for
}//End for
}//End if
fflush(Out_file);
strcpy(temp,"");
for(i=0;i<n;i++) /*Loop to obtain complete tokens*/
{
strcat(temp,Token[i]);
if(Token[i+1][0]!=','||Token[i+1][0] != ',')
strcat(temp," ");
}//End for
strcat(temp,"\n\0");
fwrite(&temp,strlen(temp),1,Out_file);
}
/*The Gen_Token function breaks the input line into tokens*/
int Gen_token(char str[], char Token[][10])
{
int i=0,j=0,k=0;
while(str[k]!='\0')
{
j=0;
while(str[k] ==' '|| str[k] =='\t')
k++;
while(str[k]!=' '&& str[k]!='\0'
&& str[k]!= '=' && str[k] != '/'
&& str[k]!= '+' && str[k] != '-'
&& str[k]!= '*' && str[k] != ',' && str[k]!= ';')
Token[i][j++] = str[k++];
Token[i++][j] = '\0';
if(str[k] == '='|| str[k] == '/'|| str[k] == '+'|| str[k]
N.Senthil Murugan AP/CSE

== '-'|| str[k] == '*'|| str[k] == '*'|| str[k] == ','||


str[k] == ';')
{
Token[i][0] = str[k++];
Token[i++][1] = '\0';
}//End if
if (str[k] == '\0')
break;
}//End while
return i;
}
INPUT : input.c
main()
{
float ti=8.14,r,a;
a = ti*r*ti;
printf(a = %f,a);
return 0;
}
OUTPUT : output.c
main()
{
float ti = 8.14, r, a ;
a = 8.14 * r * 8.14 ;
printf(a = %f, a) ;
return 0 ;
}

Alternate way through CMD

Click on Execute CMD directly button in the IDE.

Compile the Lex File by typing the command lex <filename>.l

Build the Lex File by gcc/cc command in the CMD e.g gcc lex.yy.c -o
<executable name for program>

Execute the program by typing <executable name for the


program>.exe

The -o <executable name for program> parameter is optional, you


can skip the said parameter by directly building by gcc lex.yy.c
and then directly execute your program by typing a.exe

N.Senthil Murugan AP/CSE

Alternate way through CMD

Click on the Execute CMD button in the IDE.

Compile Yacc file by typing command yacc -dy <filename.y>

Compile the Lex File by typing the command lex <filename>.l

Build the Lex File by gcc/cc command in the CMD e.g gcc lex.yy.c
y.tab.c -o <executable name for program>

Execute the program by typing <executable name for the


program>.exe

The -o <executable name for program> parameter is optional, you


can skip the said parameter by directly building by gcc lex.yy.c y.tab.c
and then directly execute your program by typing a.exe

N.Senthil Murugan AP/CSE

You might also like