You are on page 1of 67

INDEX

Exp.No. Date Title of the Experiment Page No. Signature

01 30.01.2024 Implementation of Pass I of Two pass Assembler 01

02 30.01.2024 Implementation of Pass II of Two pass Assembler 05

03 02.02.2024 Design of Macro Processor 08

04 02.02.2024 Implementation of Lexical Analyzer 11

05 06.02.2024 Conversion from Regular Expression to NFA 14

06 13.02.2024 Conversion from NFA to DFA 17

a) Left Recursion 22
07 12.03.2024
b) Design of Macro Processor 25

08 12.03.2024 FIRST and FOLLOW Computation 27

09 19.03.2024 Computation of LR(0) items 30

10 26.03.2024 Intermediate code generation – Postfix, Prefix 36


Exp.No. Date Title of the Experiment Page No. Signature

Intermediate code generation – Quadruple, Triple,


11 02.04.2024 40
Indirect triple

12 02.04.2024 A simple code Generator 45

13 12.04.2024 Implementation of DAG 48

14 12.04.2024 Implementation of Global Data Flow Analysis 52

a) Implementation Of Storage Allocation - Stack 54


15 19.04.2024
b) Implementation Of Storage Allocation - Heap 57
EX NO : 01 IMPLEMENTATION OF PASS I OF TWO PASS ASSEMBLER

DATE :

AIM:
To write a c program to perform the first pass of a two pass assembler.

ALGORITHM:

❖ Start the program.


❖ Get the assembly language program and the optab.
❖ Display the symbol names along with its address in the symbol table.
❖ Display the assembly language program along with its address in the intermediate file.
❖ Stop the program.

PROGRAM:

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

struct instruction
{
char symbol[10];
char opcode[10];
}in;

struct opcode
{
char opcode[10];
char val[10];
}op;

void main()
{
FILE *fin, *flab, *fsym, *fint;
int locctr;
int length;
int val;
char val1[10];
int len;
char operand[10];
int startadd;

clrscr();

1
fin = fopen("inp.c", "r");
flab = fopen("optab.c", "r");
fsym = fopen("symb.c", "w");
fint = fopen("inter.c", "w");

fscanf(fin, "%s%s", in.symbol, in.opcode);

while (!feof(fin))
{
if (strcmp(in.symbol, "-") != 0 && strcmp(in.opcode, "START") != 0)
{
fprintf(fsym, "%s\t%d\n", in.symbol, locctr);
}

if (strcmp(in.opcode, "START") == 0)
{
printf("START\n");
fscanf(fin, "%d", &val);
printf("val=%d\n", val);
locctr = val;
startadd = val;
fscanf(fin, "%s%s", in.symbol, in.opcode);

if (strcmp(in.symbol, "-") != 0)
{
fprintf(fsym, "%s\t%d\n", in.symbol, locctr);
}
}

rewind(flab);

while (!feof(flab))
{
fscanf(flab, "%s%s", op.opcode, op.val);

if (strcmp(op.opcode, in.opcode) == 0)
{
printf("instruction\n");
fscanf(fin, "%s", operand);
fprintf(fint, "%d\t%s\t%s\t%s\n", locctr, in.symbol, in.opcode, operand);
locctr = locctr + 3;
}
}

if (strcmp(in.opcode, "WORD") == 0);


{
printf("WORD\n");
fscanf(fin, "%d", &val);
fprintf(fint, "%d\t%s\t%s\t%d\n", locctr, in.symbol, in.opcode, val);
locctr = locctr + 3;

2
}
else if (strcmp(in.opcode, "BYTE") == 0)
{
printf("BYTE\n");
fscanf(fin, "%s", val1);
fprintf(fint, "%d\t%s\t%s\t%s\n", locctr, in.symbol, in.opcode, val1);

if (val1[0] == 'c')
{
len = strlen(val1);
locctr = locctr + len - 1;
}
else
{
locctr += 1;
}
}
else if (strcmp(in.opcode, "RESW") == 0)
{
printf("RESW\n");
fscanf(fin, "%d", &val);
fprintf(fint, "%d\t%s\t%s\t%d\n", locctr, in.symbol, in.opcode, val);
locctr = locctr + 3 * val;
}
else if (strcmp(in.opcode, "RESB") == 0)
{
printf("RESB\n");
fscanf(fin, "%d", &val);
fprintf(fint, "%d\t%s\t%s\t%d\n", locctr, in.symbol, in.opcode, val);
locctr = locctr + val;
}
else if (strcmp(in.opcode, "END") == 0)
{
printf("END\n");
fscanf(fin, "%s", operand);
fprintf(fint, "%d\t%s\t%s\t%s\n", locctr, in.symbol, in.opcode, operand);
length = locctr + startadd;
printf("length=%d", length);
}
fscanf(fin, "%s%s\n", in.symbol, in.opcode);
}

fclose(fin);
fclose(fsym);
fclose(fint);
fclose(flab);

getch();
}

3
INPUT:
COPY START 1000
FIRST LDA ALPHA
ADD ONE
_ SUB INCR
_ STA BETA
_ BYTE X'F1'
ALPHA RESW 1
ONE RESW 1
INCR RESW 1
BETA RESW 1
_ END FIRST
OPTAB:
LDA 00
ADD 18
SUB 0C
STA 1C

OUTPUT:

SYMBOL TABLE:
1000 START
1003 LDA
1006 ADD
1009 SUB
1012 STA
1013 BYTE

INTERMEDIATE FILE:
1000 FIRST LDA ALPHA
1003 _ ADD INCR
1006 _ SUB ONE
1009 _ STA BETA
1012 ONE BYTE X’F1’
1013 ALPHA RESW 1
1016 INCR RESW 1
1019 BETA RESW 1
1022 _ END FIRST

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

4
EX NO : 02 IMPLEMENTATION OF PASS II OF TWO PASS ASSEMBLER

DATE :

AIM:
To write a c program to perform pass two of two pass assembler.

ALGORITHM:

❖ Start the program.


❖ Get the intermediate file from pass one of the two pass assembler.
❖ Display the opcode values along with its address.
❖ Stop the program.

PROGRAM:

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

struct instruction
{
int addr;
char symbol[10];
char opcode[10];
} in;
struct opcode
{
char opcode[10];
char val[10];
} op;
struct symbol
{
char label[10];
int addr;
} s;
void main()
{
FILE *ftab, *fint, *fsym, *fout;
char val1[10], temp1[10];
int val, address;
clrscr();
fint = fopen("inter.c", "r");
fout = fopen("output.c", "w");
fscanf(fint, "%d%s%s", &in.addr, in.symbol, in.opcode);
while (!feof(fint))
{

5
if (strcmp(in.opcode, "WORD") == 0)
{
fscanf(fint, "%d", &val);
fprintf(fout, "%d\t%d\n", in.addr, val);
}
else if (strcmp(in.opcode, "BYTE") == 0)
{
fscanf(fint, "%s", val1);
fprintf(fout, "%d\t%s\n", in.addr, val1);
} else if (strcmp(in.opcode, "RESSW") == 0) {
fscanf(fint, "%d", &val);
}
else if (strcmp(in.opcode, "RESB") == 0)
{
fscanf(fint, "%d", &val);
}
else if (strcmp(in.opcode, "END") == 0)
{
fscanf(fint, "%s", val1);
} else {
fscanf(fint, "%s", val1);
ftab = fopen("optab.c", "r");
fscanf(ftab, "%s%s", op.opcode, op.val);
while (!feof(ftab))
{
if (strcmp(in.opcode, op.opcode) == 0)
{
strcpy(temp1, op.val);
} fscanf(ftab, "%s%s", op.opcode, op.val); }
fclose(ftab);
fsym = fopen("symb.c", "r");
fscanf(fsym, "%s%d", s.label, &s.addr);
while (!feof(fsym))
{
if (strcmp(val1, s.label) == 0)
{
address = s.addr;
}
fscanf(fsym, "%s%d", s.label, &s.addr);
}
fclose(fsym);
fprintf(fout, "%d\t%s\n", in.addr, temp1, address);
} fscanf(fint, "%d%s%s", &in.addr, in.symbol, in.opcode);
}
printf("OBJECT PROGRAM IS STORED IN OUTPUT.C\n");
getch();
}

6
INPUT:

INTERMEDIATE FILE:
1000 FIRST LDA ALPHA
1003 _ ADD INCR
1006 _ SUB ONE
1009 _ STA BETA
1012 ONE BYTE X’F1’
1013 ALPHA RESW 1
1016 INCR RESW 1
1019 BETA RESW 1
1022 _ END FIRST

OUTPUT:

1003 18
1006 1C
1009 1C
1012 1C
1013 X’F1’
1016 1C
1019 1C

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

7
EX NO : 03 DESIGN OF MACRO PROCESSOR

DATE :

AIM:
To write a c program to perform macro substitution.

ALGORITHM:

❖ Start the program.


❖ Get the assembly language program as input.
❖ When the macro name occurs, substitute the contents of the macro.
❖ Stop the program.

PROGRAM:

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

struct ins
{
char symbol[10];
char opcode[10];
char val[10];
} i;

void main()
{
FILE *fp, *fin;
char temp[10];
char name[10][10];
int j, t, i1, totmac = 0;

clrscr();

fin = fopen("inmac.c", "r");


fscanf(fin, "%s%s%s", i.symbol, i.opcode, i.val);

while (!feof(fin))
{
if (strcmp(i.opcode, "MACRO") == 0)
{
totmac += 1;
strcpy(name[totmac], i.symbol);
fp = fopen(i.symbol, "w");

8
while (strcmp(i.opcode, "MEND") != 0)
{
fprintf(fp, "%s\t%s\t%s\n", i.symbol, i.opcode, i.val);
fscanf(fin, "%s%s%s", i.symbol, i.opcode, i.val);
}

fclose(fp);
}
else
{
t = 0, j = 0;

for (i1 = 1; i1 <= totmac; i1++)


{
if (strcmp(i.opcode, name[i1]) == 0)
{
t = 1;
fp = fopen(i.opcode, "r");
printf(".");
fscanf(fp, "%s", temp);

while (!feof(fp))
{
j++;
printf("%s\t", temp);

if (j == 3)
{
printf("%s\n", temp);
j = 0;
}

fscanf(fp, "%s", temp);


}
}
}
if (t == 0)
{
if (j < 3)
printf("%s\t%s\t%s\n", i.symbol, i.opcode, i.val);
}
}
fscanf(fin, "%s%s%s", i.symbol, i.opcode, i.val);
}

getch();
}

9
INPUT:

COPY START 1000


A1 MACRO _
_ LDA ALPHA
_ SUB ONE
_ STA BETA
_ MEND _
FIRST CLEAR A
_ A1 _

ALPHA RESW 1
INCR RESW 1
ONE WORD 1
BETAR RESW 1
_ END FIRST

OUTPUT:

COPY START 1000 FIRST CLEAR A


.A1 MACRO _
_ LDA ALPHA
_ SUB ONE
_ STA BETA ALPHA RESW 1
INCR RESW 1
ONE WORD 1
BETAR RESW 1
_ END FIRST

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

10
EX NO : 04 IMPLEMENTATION OF LEXICAL ANALYZER

DATE :

AIM:
To write a C program to implement Lexical Analyzer.

ALGORITHM:

❖ Start
❖ Get C program input file.
❖ Read the contents of file character by character into ch.
❖ If op contains ch, print operator.
❖ If pun contains ch, print punctuation.
❖ If ch is alphanumeric, store in buffer buf and read the next character.
❖ Store ch until whitespace or new line is encountered.
❖ If the keyword contains buf, print the keyword.
❖ If isdigit(buf) is true, print digit.
❖ Else, print

PROGRAM:

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

int iskeyword(char buf[])


{
char keyword[11][10] = {"int", "float", "for", "while", "if", "else", "do", "double",
"return", "void", "main"};
int i, flag = 0;

for(i = 0; i < 11; i++)


{
if(strcmp(keyword[i], buf) == 0)
{
flag = 1;
break;
}
}
return flag;
}

11
void main()
{
char op[7] = {'+', '-', '=', '*', '/', '%', '&'};
char pun[3] = {',', ';', '!'};
char ch, buf[15], name[10];
FILE *fp;
int i, j = 0;

clrscr();

printf("Enter file name: ");


scanf("%s", name);
fp = fopen(name, "r");

while ((ch = fgetc(fp)) != EOF)


{
for (i = 0; i < 7; i++)
if (ch == op[i])
printf("\n%c: operator", ch);

for (i = 0; i < 3; i++)


if (ch == pun[i])
printf("\n%c: punctuation", ch);

if (isalnum(ch))
buf[j++] = ch;
else if ((ch == ' ' || ch == '\n') && (j != 0))
{
buf[j] = '\0';
j = 0;

if (iskeyword(buf) == 1)
printf("\n%s: keyword", buf);
else if ((int)buf[0] >= 48 && (int)buf[0] <= 57)
printf("\n%s: digit", buf);
else
printf("\n%s: identifier", buf);
}
}

fclose(fp);
getch();
}

12
OUTPUT:

RESULT:
Thus, the C program to implement lexical analyzer has been executed and the output
has been verified successfully.

13
EX NO : 05 REGULAR EXPRESSION TO NFA

DATE :

AIM:
To write a program to convert Regular Expression to NFA.

ALGORITHM:

❖ Start
❖ Get input of the regular expression.
❖ Read input character by character into s.
❖ If s is alphabet, store in ret[].
❖ If s is ‘.’, ‘+’, ‘*’, determine transition inputs according to Thompson’s Construction.
❖ Store the transition inputs in ret.
❖ Display the output.

PROGRAM:

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

int ret[100];
static int pos = 0;
static int sc = 0;

void nfa(int st, int p, char* s)


{
int i, sp, fs[15], fsc = 0;
sp = st;
pos = p;
sc = st;

while (*s != NULL)


{
if (isalpha(*s))
{
ret[pos++] = sp;
ret[pos++] = *s;
ret[pos++] = ++sc;
}
if (*s == '.')
{
sp = sc;

14
ret[pos++] = sc;
ret[pos++] = 238;
ret[pos++] = ++sc;
sp = sc;
}

if (*s == '+')
{
sp = st;
fs[fsc++] = sc;
}

if (*s == '*')
{
ret[pos++] = sc;
ret[pos++] = 238;
ret[pos++] = sp;
ret[pos++] = sp;
ret[pos++] = 238;
ret[pos++] = sc;
}

if (*s == '(')
{
char ps[50];
int i = 0, flag = 1;
s++;

while (flag != 0)
{
ps[i++] = *s;

if (*s == '(')
flag++;

if (*s == ')')
flag--;

s++;
}
ps[--i] = '\0';
nfa(sc, pos, ps);
s--;
}
s++;
}

sc++;
}

15
void main()
{
int i;
char *inp;

printf("\nEnter the regular expression: ");


gets(inp);
nfa(1, 0, inp);

printf("\nState Input State\n");


for (i = 0; i < pos; i += 3)
printf("%d --> %c --> %d\n", ret[i], ret[i + 1], ret[i + 2]);

printf("\n");
getch();
}

OUTPUT:

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

16
EX NO : 06 CONVERSION OF NFA TO DFA

DATE :

AIM:
To write a program to convert NFA to DFA.

ALGORITHM:

❖ Start
❖ Get the input for NFA transitions.
❖ Determine the closure of the input state.
❖ Find the states that can be traversed from present for each input symbol.
❖ If any new state is found, take it as the current state and repeat step 4.
❖ Repeat steps 4 and 5 until no new state is found.
❖ Display the DFA table.

PROGRAM:

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

char nfa[50][50], s[20], st[10][20], eclos[20], input[20];


int x, e, top = 0, topd = 0, n = 0, ns, nos, in;

int checke(char a)
{
int i;

for (i = 0; i < e; i++)


{
if (eclos[i] == a)
return i;
}

return -1;
}

int check(char a)
{
int i;

for (i = 0; i < in; i++)


{
if (input[i] == a)

17
return i;
}

return -1;
}

void push(char a)
{
s[top] = a;
top++;
}

char pop()
{
top--;
return s[top];
}

void pushd(char *a)


{
strcpy(st[topd], a);
topd++;
}

char *popd()
{
topd--;
return st[topd];
}

int ctoi(char a)
{
int i = a - 48;
return i;
}

char itoc(int a)
{
char i = a + 48;
return i;
}

char *eclosure(char *a)


{
int i, j;
char c;
for (i = 0; i < strlen(a); i++)
push(a[i]);
e = strlen(a);
strcpy(eclos, a);

18
while (top != 0)
{
c = pop();

for (j = 0; j < ns; j++)


{
if (nfa[ctoi(c)][j] == 'e')
{
if (check(itoc(j)) == -1)
{
eclos[e] = itoc(j);
push(eclos[e]);
e++;
}
}
}
}

eclos[e] = '\0';
return eclos;
}

void main()
{
int i, j, k, count;
char ec[20], a[20], b[20], c[20], dstates[10][10];

clrscr();

printf("Enter the number of states\n");


scanf("%d", &ns);
for (i = 0; i < ns; i++)
{
for (j = 0; j < ns; j++)
{
printf("Move [%d][%d]:", i, j);
scanf("%s", &nfa[i][j]);

if (nfa[i][j] != '-' && nfa[i][j] != 'e')


{
if ((check(nfa[i][j])) == -1)
input[in++] = nfa[i][j];
}
}
}

d = 0;
nos = 0;
c[0] = itoc(0);
c[1] = '\0';

19
pushd(eclosure(c));
strcpy(dstates[nos], eclosure(c));
for (x = 0; x < in; x++)
printf("\t%c", input[x]);

printf("\n");
while (topd > 0)
{
strcpy(a, popd());
printf(" %s", a);
for (i = 0; i < in; i++)
{
int len = 0;

for (j = 0; j < strlen(a); j++)


{
int x = ctoi(a[j]);

for (k = 0; k < ns; k++)


{
if (nfa[x][k] == input[i])
ec[len++] = itoc(k);
}
}
ec[len] = '\0';
strcpy(b, eclosure(ec));
count = 0;

for (j = 0; j <= nos; j++)


{
if (strcmp(dstates[j], b) == 0)
count++;
}
if (count == 0)
{
if (b[0] != '\0')
{
nos++;
pushd(b);
strcpy(dstates[nos], b);
}
}
printf("\t%s", b);
}
printf("\n");
}
getch();
}

20
OUTPUT:

RESULT:
Thus, the C program to convert NFA to DFA has been executed and the output has
been verified successfully.

21
EX NO : 07 a) LEFT RECURSION
DATE :

AIM:
To write a program to perform Left recursion.

ALGORITHM:

❖ For each nonterminal :


➢ a. Repeat until an iteration leaves the grammar unchanged:
➢ b. For each rule, being a sequence of terminals and non terminals.
❖ If begins with a nonterminal and :
➢ a. Let be without its leading.
➢ b. Remove the rule.
➢ c. For each rule :
➢ d. Add the rule.
❖ Remove direct left recursion as described above.

PROGRAM:

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

int main()
{
int i, j, n, k;
int lrec = 0;
char prod[100];
char newprod1[100] = "";
char newprod2[100] = "";
char alpha[100] = "";
char beta[100] = "";
char sts[20] = "";

scanf("%s", prod);

sts[0] = prod[0]; // sts is Start Symbol


int size = (int)(strlen(prod));

for(i = 0; i < size; i++)


{
if(prod[i] == '|')
{
k = i;
}

22
}

if(prod[3] == prod[0]) // E->E+T


{
lrec = 1;
}

if(lrec == 1)
{
int c = 0;
k = k - 1;

for(i = 4; i <= k; i++)


{
alpha[c] = prod[i];
c++;
}

c = 0;

for(i = k + 2; i < size; i++)


{
beta[c] = prod[i];
c++;
}

strcat(newprod1, sts); // -,E


strcat(newprod1, "->");
strcat(newprod1, beta); // T
strcat(newprod1, sts); // E
strcat(newprod1, "'"); // E'

strcat(newprod2, sts); // E
strcat(newprod2, "'"); // E'
strcat(newprod2, "->");
strcat(newprod2, alpha); // +T
strcat(newprod2, sts); // E
strcat(newprod2, "'"); // '
strcat(newprod2, "|e"); // |e

printf("\n%s\n%s", newprod1, newprod2); // E->TE'


}

return 0;
}

23
OUTPUT:

RESULT:
Thus, the C program to remove Left recursion in the given grammar has been
executed and the output has been verified successfully.

24
EX NO : 07 b) DESIGN OF MACRO PROCESSOR

DATE :

AIM:
To write a program to Design a Macro Processor.

ALGORITHM:

❖ For each non terminal A, find the longest prefix α common to two or more of its
alternatives.
❖ If α!= E,i. e., there is a non trivial common prefix, replace all the A productions.
❖ A-> αβ1| αβ2|…………..| αβn| ɣ where ɣ represents all alternatives that do not begin
with α by
❖ A==> α A’| ɣ
❖ A’==>β1|β2|………….|βn
❖ Here A’ is a new non terminal. Repeatedly apply this transformation until no two
alternatives for a non-terminal have a common prefix.

PROGRAM:

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

int main()
{
char a[10], a1[10], a2[10], a3[10], a4[10], a5[10];
int i, j = 0, k, l;

printf("Enter any productions A->");


gets(a);

for(i = 0; a[i] != '|'; i++, j++)


a1[j] = a[i];

a1[j] = '\0';

for(j = ++i, i = 0; a[j] != '\0'; j++, i++)


a2[i] = a[j];

a2[i] = '\0';
k = 0;
l = 0;

for(i = 0; i < strlen(a1) || i < strlen(a2); i++)

25
{
if(a1[i] == a2[i])
{
a3[k] = a1[i];
k++;
}
else
{
a4[l] = a1[i];
a5[l] = a2[i];
l++;
}
}

a3[k] = 'A';
a3[++k] = '\0';
a4[l] = '|';
a5[l] = '\0';
a4[++l] = '\0';

printf("\n A->%s'", a3);


printf("\n A'->%s|\356", a5);

return 0;
}

OUTPUT:

RESULT:
Thus, the C program to generate left factored grammar has been executed and the
output has been verified successfully.

26
EX NO : 08 COMPUTATION OF FIRST AND FOLLOW SETS

DATE :

AIM:
To write a program to compute first and follow sets of grammar productions.

ALGORITHM:

❖ Start
❖ Check whether the first element of a non-terminal production is a terminal.
❖ If true, add it to First(NT).
❖ For Follow, check if the NT exists on RHS of any production.
If next symbol is
➢ NT, then add First(NT) to Follow.
➢ T, add T to Follow.
➢ Nothing, then add Follow(source) to Follow.

PROGRAM:

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

int n, m = 0, p, i = 0, j = 0;
char a[10][10], f[10];

void follow(char c);


void first(char c);

void main()
{
int i, z;
char c, ch;

clrscr();

printf("Enter the number of productions:\n");


scanf("%d", &n);

printf("Enter the productions:\n");

for (i = 0; i < n; i++)


scanf("%s%c", a[i], &ch);

27
do
{
m = 0;

printf("Enter the elements whose first & follow is to be found:");


scanf("%c", &c);
first(c);
printf("First(%c)={", c);

for (i = 0; i < m; i++)


printf("%c", f[i]);

printf("}\n");
strcpy(f, " ");
flushall();
m = 0;
follow(c);

printf("Follow(%c)={", c);

for (i = 0; i < m; i++)


printf("%c", f[i]);

printf("}\n");

printf("Continue(0/1)?");
scanf("%d%c", &z, &ch);
} while (z == 1);
getch();
}
void first(char c)
{
int k;
if (!isupper(c))
f[m++] = c;

for (k = 0; k < n; k++)


if (a[k][0] == c)
{
if (a[k][2] == '$')
follow(a[k][0]);
else if (islower(a[k][2]))
f[m++] = a[k][2];
else
first(a[k][2]);
}
}
void follow(char c)
{
if (a[0][0] == c)

28
f[m++] = '$';

for (i = 0; i < n; i++)


{
for (j = 2; j < strlen(a[i]); j++)
{
if (a[i][j] == c)
{
if (a[i][j + 1] != '\0')
first(a[i][j + 1]);

if (a[i][j + 1] == '\0' && c != a[i][0])


follow(a[i][0]);
}
}
}
}

OUTPUT:

RESULT:
Thus, the C program to compute First( ) and Follow( ) for the non-terminals of a
given CFG has been executed and the output has been verified successfully.

29
EX NO : 09 COMPUTATION OF LR(0)

DATE :

AIM:
To write a program to compute LR(0) items.

ALGORITHM:

❖ Start
❖ Generate augmented grammar.
❖ Start with C0 by including all marked productions [S->.α]
❖ Compute the closure of item set C0
❖ Perform a read operation on items in an item set.
❖ Compute the closure of the new item set.
❖ Continue reading until all .S have travelled through all item sets

PROGRAM:

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

char prod[20][20], listofvar[26] = "ABCDEFGHIJKLMNOPQR";


int novar = 1, i = 0, j = 0, k = 0, n = 0, m = 0, arr[30];
int noitem = 0;

struct Grammar
{
char lhs;
char rhs[8];
} g[20], item[20], clos[20][10];
int isvariable(char variable)
{
for (int i = 0; i < novar; i++)
if (g[i].lhs == variable)
return i + 1;
return 0;
}
void findclosure(int z, char a)
{
int n = 0, i = 0, j = 0, k = 0, l = 0;

for (i = 0; i < arr[z]; i++)


{
for (j = 0; j < strlen(clos[z][i].rhs); j++)

30
{
if (clos[z][i].rhs[j] == '.' && clos[z][i].rhs[j + 1] == a)
{
}
}
}
clos[noitem][n].lhs = clos[z][i].lhs;
strcpy(clos[noitem][n].rhs, clos[z][i].rhs);
char temp = clos[noitem][n].rhs[j];
clos[noitem][n].rhs[j] = clos[noitem][n].rhs[j + 1];
clos[noitem][n].rhs[j + 1] = temp;
n = n + 1;
for (i = 0; i < n; i++)
{
for (j = 0; j < strlen(clos[noitem][i].rhs); j++)
{
if (clos[noitem][i].rhs[j] == '.' && isvariable(clos[noitem][i].rhs[j + 1]) > 0)
{
for (k = 0; k < novar; k++)
{
if (clos[noitem][i].rhs[j + 1] == clos[0][k].lhs)
{
for (l = 0; l < n; l++)
if (clos[noitem][l].lhs == clos[0][k].lhs && strcmp(clos[noitem][l].rhs,
clos[0][k].rhs) == 0)
break;
if (l == n)
{
clos[noitem][n].lhs = clos[0][k].lhs;
strcpy(clos[noitem][n].rhs, clos[0][k].rhs);
n = n + 1;
}
}
}
}
}
}
arr[noitem] = n;
int flag = 0;
for (i = 0; i < noitem; i++)
{
if (arr[i] == n)
{
for (j = 0; j < arr[i]; j++)
{
int c = 0;
for (k = 0; k < arr[i]; k++)
if (clos[noitem][k].lhs == clos[i][k].lhs && strcmp(clos[noitem][k].rhs,
clos[i][k].rhs) == 0)
c = c + 1;

31
if (c == arr[i])
{
flag = 1;
goto exit;
}
}
}
}
exit:;
if (flag == 0)
arr[noitem++] = n;
}
void main()
{
clrscr();
cout << "ENTER THE PRODUCTIONS OF THE GRAMMAR(0 TO END) :\n";
do
{
cin >> prod[i++];
} while (strcmp(prod[i - 1], "0") != 0);
for (n = 0; n < i - 1; n++)
{
m = 0;
j = novar;
g[novar++].lhs = prod[n][0];
for (k = 3; k < strlen(prod[n]); k++)
{
if (prod[n][k] != '|')
g[j].rhs[m++] = prod[n][k];
if (prod[n][k] == '|')
{
g[j].rhs[m] = '\0';
m = 0;
j = novar;
g[novar++].lhs = prod[n][0];
}
}
}

for (i = 0; i < 26; i++)


if (!isvariable(listofvar[i]))
break;
g[0].lhs = listofvar[i];
char temp[2] = {g[1].lhs, '\0'};
strcat(g[0].rhs, temp);
cout << "\n\n augumented grammar \n";

for (i = 0; i < novar; i++)


cout << endl
<< g[i].lhs << "->" << g[i].rhs << " ";

32
getch();
for (i = 0; i < novar; i++)
{
clos[noitem][i].lhs = g[i].lhs;
strcpy(clos[noitem][i].rhs, g[i].rhs);

if (strcmp(clos[noitem][i].rhs, "ε") == 0)
strcpy(clos[noitem][i].rhs, ".");
else
{
for (int j = strlen(clos[noitem][i].rhs) + 1; j >= 0; j--)
clos[noitem][i].rhs[j] = clos[noitem][i].rhs[j - 1];

clos[noitem][i].rhs[0] = '.';
}
}
arr[noitem++] = novar;
for (int z = 0; z < noitem; z++)
{
char list[10];
int l = 0;

for (j = 0; j < arr[z]; j++)


{
for (k = 0; k < strlen(clos[z][j].rhs) - 1; k++)
{
if (clos[z][j].rhs[k] == '.')
{
for (
m = 0; m < l; m++)
if (list[m] == clos[z][j].rhs[k + 1])
break;
if (m == l)
list[l++] = clos[z][j].rhs[k + 1];
}
}
}
for (int x = 0; x < l; x++)
findclosure(z, list[x]);
}
cout << "\n THE SET OF ITEMS ARE \n\n";
for (z = 0; z < noitem; z++)
{
cout << "\n I" << z << "\n\n";
for (j = 0; j < arr[z]; j++)
cout << clos[z][j].lhs << "->" << clos[z][j].rhs << "\n";
getch();
}
getch();
}

33
OUTPUT:

34
RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

35
EX NO : 10 INTERMEDIATE CODE GENERATION- THREE ADDRESS
CODES
DATE :

AIM:
To write a C Program to generate a three address code.

ALGORITHM:

❖ Initially check the choice of the user


❖ Assignment shows how it is assigned in three address code
❖ Arithmetic shows how it solves in three address code
❖ Relational shows how it proves the relations in three address code
❖ Stop the program by exit

PROGRAM:

#include"stdio.h"
#include"conio.h"
#include"string.h"
#include"process.h"

int i = 1, j = 0, no = 0, tmpch = 90;


char str[100], left[15], right[15];

struct exp
{
int pos;
char op;
} k[15];

void findopr();
void explore();
void fleft(int);
void fright(int);

void main()
{
printf("Enter the Expression :- ");
scanf("%s", str);
printf("The Intermediate code:\t\tExpression\n");
findopr();
explore();
getch();
}

36
void findopr()
{
for (i = 0; str[i] != '\0'; i++)
if (str[i] == ':')
{
k[j].pos = i;
k[j++].op = ':';
}
for (i = 0; str[i] != '\0'; i++)
if (str[i] == '/')
{
k[j].pos = i;
k[j++].op = '/';
}
for (i = 0; str[i] != '\0'; i++)
if (str[i] == '*')
{
k[j].pos = i;
k[j++].op = '*';
}
for (i = 0; str[i] != '\0'; i++)
if (str[i] == '+')
{
k[j].pos = i;
k[j++].op = '+';
}
for (i = 0; str[i] != '\0'; i++)
if (str[i] == '-')
{
k[j].pos = i;
k[j++].op = '-';
}
}
void explore()
{
i = 1;
while (k[i].op != '\0')
{
fleft(k[i].pos);
fright(k[i].pos);
str[k[i].pos] = tmpch--;
printf("\t%c := %s%c%s\t\t", str[k[i].pos], left, k[i].op, right);

for (j = 0; j < strlen(str); j++)


if (str[j] != '$')
printf("%c", str[j]);
printf("\n");
i++;
}
fright(-1);

37
if (no == 0)
{
fleft(strlen(str));
printf("\t%s := %s", right, left);
getch();
exit(0);
}
printf("\t%s := %c", right, str[k[--i].pos]);
getch();
}
void fleft(int x)
{
int w = 0, flag = 0;
x--;

while (x != -1 && str[x] != '+' && str[x] != '*' && str[x] != '=' && str[x] != '\0'
&& str[x] != ' ' && str[x] != '/' && str[x] != ':')
{
if (str[x] != '$' && flag == 0)
{
left[w++] = str[x];
left[w] = '\0';
str[x] = '$';
flag = 1;
}
x--;
}
}
void fright(int x)
{
int w = 0, flag = 0;
x++;
while (x != -1 && str[x] != '+' && str[x] != '*' && str[x] != '\0' && str[x] != '='
&& str[x] != ':' && str[x] != '-' && str[x] != '/')
{
if (str[x] != '$' && flag == 0)
{
right[w++] = str[x];
right[w] = '\0';
str[x] = '$';
flag = 1;
}
x++;
}
}

38
OUTPUT:

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

39
EX NO : 11 INTERMEDIATE CODE GENERATION - PREFIX, POSTFIX

DATE :

AIM:
To write a program to convert infix expression to postfix and prefix expression.

ALGORITHM:

❖ Scan the infix expression from left to right.


❖ If the scanned character is an operand, output it.
❖ Else,
➢ If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty), push it.
➢ Else, Pop the operator from the stack until the precedence of the scanned
operator is less-equal to the precedence of the operator residing on the top of
the stack. Push the scanned operator to the stack.
❖ If the scanned character is an ‘(‘, push it to the stack.
❖ If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is
encountered.
❖ Repeat steps 2-6 until the infix expression is scanned.
❖ Pop and output from the stack until it is not empty. Output is a postfix expression.
❖ Reverse the infix string.
❖ Apply infix to postfix operations.
❖ Reversed output string is a prefix expression.

PROGRAM:

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

int pop();
int precedence(char symbol);
int isEmpty();
void infix_to_prefix();
void infix_to_postfix();
int checker(char symbol);
void push(long int symbol);

40
char prefix_string[20], infix_string[20], postfix_string[20];
int top;
long int stack[20];

int main()
{
int i, length;
char temp;
top = -1;
clrscr();
printf("\nEnter an Expression in Infix format:\t");
scanf("%[^\n]s", infix_string);
infix_to_postfix();
printf("\nExpression in Postfix Format: \t%s\n", postfix_string);
strrev(infix_string);
infix_to_prefix();
strrev(postfix_string);
strcpy(prefix_string, postfix_string);
length = strlen(prefix_string);
printf("\nExpression in Prefix Format: \t");
for (i = 0; i < length; i++)
if (prefix_string[i] != '(' && prefix_string[i] != ')')
printf("%c", prefix_string[i]);
getch();
return 0;
}

void infix_to_postfix()
{
unsigned int count, temp = 0;
char next;
char symbol;
for (count = 0; count < strlen(infix_string); count++)
{
symbol = infix_string[count];
if (!checker(symbol))
switch (symbol)
{
case '(':
push(symbol);
break;
case ')':
while ((next = pop()) != '(')
postfix_string[temp++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':

41
case '^':
while (!isEmpty() && precedence(stack[top]) >= precedence(symbol))
postfix_string[temp++] = pop();
push(symbol);
break;
default:
postfix_string[temp++] = symbol;
}
}
while (!isEmpty())
postfix_string[temp++] = pop();
postfix_string[temp] = '\0';
}
void infix_to_prefix()
{
unsigned int count, temp = 0;
char next;
char symbol;
for (count = 0; count < strlen(infix_string); count++)
{
symbol = infix_string[count];
if (!checker(symbol))
switch (symbol)
{
case ')':
push(symbol);
break;
case '(':
while ((next = pop()) != ')')
postfix_string[temp++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while (!isEmpty() && precedence(stack[top]) >= precedence(symbol))
postfix_string[temp++] = pop();
push(symbol);
break;
default:
postfix_string[temp++] = symbol;
}
}
while (!isEmpty())
postfix_string[temp++] = pop();
postfix_string[temp] = '\0';
}

42
int precedence(char symbol)
{
switch (symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default:
return 0;
}
}
int checker(char symbol)
{
if (symbol == '\t' || symbol == ' ')
return 1;
return 0;
}
void push(long int symbol)
{
if (top > 20)
{
printf("Stack Overflow\n");
exit(1);
}
top = top + 1;
stack[top] = symbol;
}
int isEmpty()
{
if (top == -1)
return 1;
return 0;
}
int pop()
{
if (isEmpty())
{
printf("Stack is Empty\n");
exit(1);
}
return (stack[top--]);
}

43
OUTPUT:

RESULT:
Thus, the C program to convert the given infix to prefix and postfix expression has
been executed and the output has been verified successfully.

44
EX NO : 12 SIMPLE CODE GENERATOR

DATE :

AIM:
To write a program to generate simple code.

ALGORITHM:

❖ Start Get address code sequence.


❖ Determine current location of 3 using address (for 1st operand).
❖ If the current location does not already exist generate move (B,O).
❖ Update address of A(for 2nd operand).
❖ If the current value of B and () is null, exist.
❖ If they generate operator () A,3 ADPR.
❖ Store the move instruction in memory
❖ Stop

PROGRAM:

#include<iostream>
using namespace std;
#include<string.h>
#include<conio.h>

char reg[10][3] = {"R0", "R1", "R2", "R3", "R4", "R5"};


char stmt[10][10], code[15];
int nostmt = 0, i = 0, output[15];
void icode(char source[10], char dest[10], int out)
{
strcat(code, source);
strcat(code, " ");
strcat(code, dest);
output[i] = out;
cout << code << endl;
getch();
}
int main()
{
//clrscr();
int j, i;
cout << " Enter the statements(END to end): \n";
do
{
cin >> stmt[nostmt++];

45
} while (strcmp(stmt[nostmt - 1], "END") != 0);
nostmt = nostmt - 1;
cout << "\n THE INTERMEDIATE CODE IS\n\n";
for (i = 0; i < nostmt; i++)
{
strcpy(code, "");
int rd = -1, rs = -1, k;
for (j = 0; j < i; j++)
{
if (stmt[j][0] == stmt[i][2])
rs = output[j];
if (stmt[j][0] == stmt[1][4])
rd = output[j];
} if (rs == -1) {
strcpy(code, "MOV ");
char temp[2] = {stmt[i][2], '\0'};
icode(temp, reg[i], i);
}
if (stmt[i][3] == '+')
strcpy(code, "ADD ");
if (stmt[i][3] == '-')
strcpy(code, "SUB ");
if (stmt[i][3] == '*')
strcpy(code, "MUL ");
if (stmt[i][3] == '/')
strcpy(code, "DIV ");
if (rd == -1)
{
char temp[2] = {stmt[i][4], '\0'};
if (rs != -1)
k = output[rs];
else
k = i;
icode(temp, reg[k], k);
} if (rs != -1 && rd != -1) {
int flag = 0;
for (j = i; j < nostmt; j++)
if (stmt[j][2] == stmt[i][2] || stmt[j][2] == stmt[i][4])
flag = 1;
if (flag != 1)
icode(reg[output[rs]], reg[output[rd]], output[rd]);
if (flag == 1)
icode(reg[output[rd]], reg[output[rs]], output[rs]);
}
}
strcpy(code, "MOV ");
char temp[2] = {stmt[i - 1][0], '\0'};
icode(reg[output[i - 1]], temp, 0);
}

46
OUTPUT:

RESULT:
Thus, the C program to generate assembly code for the given three address code has
been executed and the output has been verified successfully.

47
EX NO : 13 IMPLEMENTATION OF DAG

DATE :

AIM:
To write a C Program to generate a Directed Acyclic Graph

ALGORITHM:

❖ Read the input String.


❖ Create a leaf node with the label for each operand - identifier.
❖ Create interior nodes with an operator symbol and pointers to left and right operands.
❖ Create a list of attached identifiers for each node to hold the computed values.
➢ Case (i) x : = y OP z
➢ Case (ii) x : = OP y
➢ Case (iii) x : = y
❖ 1: If y is undefined then create node(y).
➢ If z is undefined, create node(z) for case(i).
➢ For the case(i), create a node(OP) whose left child is node(y) and right child
isnode(z).
Let n be this node.
➢ For case(ii), determine whether there is node(OP) with one child node(y). If
not, create such a node.
➢ For case(iii), node n will be node(y).
❖ Delete x from the list of identifiers for node(x). Append x to the list of attached
identifiers for the node n found in step 3 and set node(x) to n.

PROGRAM:

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

void main()
{
struct da
{
int ptr, left, right;
char label;
} dag[25];

48
int ptr, l, j, change, n = 0, i = 0, state = 1, x, y, k;
char store, *input1, input[25], var;
clrscr();

for (i = 0; i < 25; i++)


{
dag[i].ptr = NULL;
dag[i].left = NULL;
dag[i].right = NULL;
dag[i].label = NULL;
}

printf("\n\nENTER THE EXPRESSION\n\n");


scanf("%s", input1); /*EX:((a*b-c))+(b-c))*/
a:
for (i = 0; input1[i] != ')'; i++)
;
for (j = i; input1[j] != '('; j--)
;
for (x = j + 1; x < i; x++)
if (isalpha(input1[x]))
input[n++] = input1[x];
else if (input1[x] != '0')
store = input1[x];
input[n++] = store;

for (x = j; x <= i; x++)


input1[x] = '0';

if (input1[0] != '0')
goto a;

for (i = 0; i < n; i++)


{
dag[i].label = input[i];
dag[i].ptr = i;

if (!isalpha(input[i]) && !isdigit(input[i]))


{
dag[i].right = i - 1;
ptr = i;
var = input[i - 1];

if (isalpha(var))
ptr = ptr - 2;
else
{
ptr = i - 1;
b:
if (!isalpha(var) && !isdigit(var))

49
{
ptr = dag[ptr].left;
var = input[ptr];
goto b;
}
else
ptr = ptr - 1;
}
dag[i].left = ptr;
}
}
printf("\n SYNTAX TREE FOR GIVEN EXPRESSION\n\n");
printf("\n\n PTR \t\t LEFT PTR \t\t RIGHT PTR \t\t LABEL\n\n");

for (i = 0; i < n; i++) /* draw the syntax tree for the following output with pointer
value*/
printf("\n%d\t%d\t%d\t%c\n", dag[i].ptr, dag[i].left, dag[i].right, dag[i].label);

getch();

for (i = 0; i < n; i++)


{
for (j = 0; j < n; j++)
{
if ((dag[i].label == dag[j].label && dag[i].left == dag[j].left) && dag[i].right
== dag[j].right)
{
for (k = 0; k < n; k++)
{
if (dag[k].left == dag[j].ptr)
dag[k].left = dag[i].ptr;
if (dag[k].right == dag[j].ptr)
dag[k].right = dag[i].ptr;
}
dag[j].ptr = dag[i].ptr;
}
}
}

printf("\n DAG FOR GIVEN EXPRESSION\n\n");


printf("\n\n PTR \t LEFT PTR \t RIGHT PTR \t LABEL \n\n");

for (i = 0; i < n; i++) /*draw DAG for the following output with pointer value*/
printf("\n %dt\t%d\t\t%d\t\t%c\n", dag[i].ptr, dag[i].left, dag[i].right,
dag[i].label);

getch();
}

50
OUTPUT:

RESULT:
Thus, the C program to construct DAG has been executed and the output has been
verified successfully.

51
EX NO : 14 IMPLEMENTATION OF GLOBAL DATA FLOW ANALYSIS

DATE :

AIM:
To write a C program to Implement Data Flow Analysis

ALGORITHM:

❖ Start the program execution


❖ Read the total number of expressions
❖ Read the left and right side of each expressions
❖ Display the expressions with line no
❖ Display the Data flow movement with particular expressions
❖ Stop the program execution

PROGRAM:

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

struct op {
char left[10];
char right[10];
} op2[15], prt[15];

int main() {
int a, j, i, k, n, m, q, l = 1;
char *p, *li;
char temp, t;
char *tem, *mat;
printf("enter no.of.values");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("left");
scanf("%s", op2[i].left);
printf("right");
scanf("%s", op2[i].right);
}
printf("intermediate code");
for (i = 0; i < n; i++) {
printf("Lineno=%d\n", l);
printf("%s=", op2[i].left);
printf("%s\n", op2[i].right);
l++;

52
}
printf("dataflow analysis");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
mat = strstr(op2[j].right, op2[i].left);
if (mat) {
printf("\n%s is live at %s\n", op2[i].left, op2[j].right);
}
}
}
return 0;
}

OUTPUT:

RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

53
EX NO : 15 a) IMPLEMENTATION OF STORAGE ALLOCATION - STACK

DATE :

AIM:
To implement Stack Storage Allocation Strategies using C program.

ALGORITHM:

❖ Initially check whether the stack is empty


❖ Insert an element into the stack using push operation
❖ Insert more elements onto the stack until stack becomes full
❖ Delete an element from the stack using pop operation
❖ Display the elements in the stack
❖ Stop the program by exit

PROGRAM:

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

int i, stk[100], top=-1, n;


void show() {
for(i=0; i<=top; i++)
printf("%d\t", stk[i]);
}
void push() {
int item;
if(top == n-1)
printf("\nStack is full.");
else {
printf("\nEnter the item: ");
scanf("%d", &item);
stk[++top] = item;
}
}
void pop() {
if(top == -1)
printf("Stack is empty.");
else {
printf("%d is popped.", stk[top]);
top--;
}

54
}
int main() {
int i, op;
printf("Enter the size of the stack: ");
scanf("%d", &n);
do {
printf("\n1 : Push");
printf("\n2 : Pop");
printf("\n3 : Display");
printf("\n4 : Exit");
printf("\nEnter your choice: ");
scanf("%d", &op);
switch(op) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
}
} while(op != 4);
getch();
}

OUTPUT:

55
RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

56
EX NO : 15 b) IMPLEMENTATION OF STORAGE ALLOCATION - HEAP

DATE :

AIM:
To implement Stack Storage Allocation Strategies using C program.

ALGORITHM:

❖ Initially check whether the stack is empty


❖ Insert an element into the stack using push operation
❖ Insert more elements onto the stack until stack becomes full
❖ Delete an element from the stack using pop operation
❖ Display the elements in the stack
❖ Stop the program by exit

PROGRAM:

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

#define TRUE 1
#define FALSE 0

typedef struct Heap {


int data;
struct Heap *next;
} node;

node *create();
void display(node *);
node *search(node *, int);
node *insert(node *);
void dele(node **);

int main() {
int choice, val;
char ans;
node *head;
void display(node *);
node *search(node *, int);
node *insert(node *);

57
void dele(node **);

head = NULL;

do {
printf("\n Various operations on Heap");
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("\nEnter 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:
printf("Invalid Choice, Try again");
getch();
}
} while (choice != 5);
}

node *create() {
node *temp, *new1, *head;
int val, flag;
char ans = 'y';
node *get_node();
temp = NULL;
flag = TRUE;

do {
printf("\n Enter the Element: ");
scanf("%d", &val);

new1 = get_node();

58
if (new1 == NULL)
printf("\n Memory is not allocated");

new1->data = val;

if (flag == TRUE) {
head = new1;
temp = head;
flag = FALSE;
} else {
temp->next = new1;
temp = new1;
}

printf("\nDo you want to enter more elements? (y/n)");


ans = getch();
} while (ans == 'y');

printf("\nThe list is created");


getch();

return head;
}

node *get_node() {
node *temp;
temp = (node *)malloc(sizeof(node));
temp->next = NULL;
return temp;
}

void display(node *head) {


node *temp;
temp = head;

if (temp == NULL) {
printf("\n The list is empty\n");
getch();
return;
}

while (temp != NULL) {


printf("%d->", temp->data);
temp = temp->next;
}

printf("NULL");
getch();
}

59
node *search(node *head, int key) {
node *temp;
int found;
temp = head;

if (temp == NULL) {
printf("The linked list is empty\n");
getch();
return NULL;
}

found = FALSE;

while ((temp != NULL) && (found == FALSE)) {


if (temp->data != key)
temp = temp->next;
else
found = TRUE;
}

if (found == TRUE) {
printf("\n The Element 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("\n2. Insert a node as a last node");
printf("\nEnter your choice for insertion of node (1-2): ");
scanf("%d", &choice);

switch (choice) {
case 1:
head = insert_head(head);
break;
case 2:
insert_last(head);
break;
}

60
return head;
}

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;
else {
temp = head;
New->next = temp;
head = New;
}

return head;
}

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

node *get_prev(node *head, int val) {


node *temp, *

prev;
int flag;

temp = head;

if (temp == NULL)

61
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, *prev;

temp = *head;

if (temp == NULL) {
printf("\n The list is empty\n ");
getch();
return;
}

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);
}
printf("\nThe Element is deleted\n");
getch();
}
}

62
OUTPUT:

63
64
RESULT:
Thus, the given program has been implemented successfully and the output has been
verified.

65

You might also like