0% found this document useful (0 votes)
3 views18 pages

Compiler Design Exp. File (1-5)

The document outlines a series of programming tutorials and practical exercises for students at M.M.M. University of Technology, covering topics such as character counting in text files, implementing finite automata, computing FIRST and FOLLOW sets in grammars, and removing left recursion from grammars. Each tutorial includes objectives, sample code, and expected outputs. The exercises are designed to enhance students' understanding of programming concepts and compiler design.

Uploaded by

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

Compiler Design Exp. File (1-5)

The document outlines a series of programming tutorials and practical exercises for students at M.M.M. University of Technology, covering topics such as character counting in text files, implementing finite automata, computing FIRST and FOLLOW sets in grammars, and removing left recursion from grammars. Each tutorial includes objectives, sample code, and expected outputs. The exercises are designed to enhance students' understanding of programming concepts and compiler design.

Uploaded by

itsaastha.2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

TUTORIAL/PRACTICAL NO.

INDEX
SNo Date M N T Page Remaurks
Write a prograum waing Lex to alculate l-2
Hhe no. of characters, numbar of werds cud
the no. of ineA in the given text file as ip
Wite a C qrogram to implement th 3-4
nite automatio.
Wnte C program to ompute fRsT S-9
haloslea Ound FoLLOw ot he nan terminals of
gven grammar
Wite a C program to hack the ginen
b3lba r0mmr Às LetB Recusive 3nd remaue
st ursian
Wite a progrm waing Lex to implement
Hhe set ot reguar expresien and inictt L2
sle44e acceptance of a given sting fer
a partieular resulr expresin

M.M.M. UNIVERSITY OF TECHNOLOGY, GKP.


TUTORIAL/ PRACTICALNO. 1

EXPERIMENT 1
bjective: Write a program using
Lex to caleulade the no.
ot char acters, mum
ber ot wrda and no.

of lines present in the given text Ale as


input,

rogram:
#incude <stdio.h
int char count = 0, wrdcount = 0, ine-count - 0;

{ lineCounttt char ca unttt} / Count new ines and chracters


Lt]+ {3 I/Isnore tabs and spaces
wordceunttt, char count t= yyleng)} U Count wrds cund
la-zA-Z0-9]+ charucters ntJt
{char.centtt,} Coun any other charaters
lyyieng -> holds tho lengththeof poern.
current toten imatches by

crg-info C3){
int main(nt org- ceud, char * represnts the number of
lorg ceunt (orument count)from the " Command ino"
( passed to the program of
string
(ugument Informtion) is
l arg ìnto
l containing argumanta lxrogram.l
aurgvlo) i Hhe nam ot the progcum --’
7 user-’
Hhe Ale name passed by the

fILE * ile;
/Er handling it chack Ahot no. ot arguments (program me

deAs Hhan 2
land ile nam) rm cemmand ine i
I/es, it means hane missed for arguman
any re

M.M.M.UNIVERSITY OF TECHNOLOGY,GKP.
fext. txt
Hello
Welcome to Flex|

Qutput
flex cdexpl.2
9cc Rex.yyc
\a,exe text.txt
Nunber of haacters 2L
Num ber of weT ds 4
Nenber of lines:D
TUTORIAL/PRACTICAL NO.
I/ and it pints a messag sho how to wse
it (arg-count < 2) {
print.f(eu hawe enter s 9nlay Please enter
Ahe Ale name olson, curginfo Co3
retrn L,

/Open he Ale
file = fopen (arg-info C1], "r"),

perrr ("Error epening Ale "))

variable pronided Lex


/yyin is a special glebal read input from.
tells it where to
7hat steundrd input (keybonrd
Lex reads frorn
7by defaut, it to file, so Lex will
set
I| tnput ), but here we
ile.
Il read from the
yyin = file
anasi
I/ Start lexica
yylex)i
cf cha actersi d n charcout )
prindf ("Number
prntt(Number ot wrda. , wordeco wnt)
Numbor of ines dln" ine_count
printf"

felose (file);
return 0,

int yywrap){
rehurn / Sndicate end of input

M.M.M.UNIVERSITY OF TECHNOLOGY, GKP. 2


TUTORIAL/PRACTICAL NO, 2

EXPERIMENT2
sbje ctive Write a C pruqrm to inplemnd ihe
tho cowesin
of
egutar expreasten to non deterministic tinite
dutmatian,

*incde <stdio, h>


tinclud¢e <ståub.h
tincude <stingh
*de fine MAX io0
typedef sfhuct f
int start,
i t end,
char transitio,

ypedef strut i
Edge edyes [MAX],
t edgeluint
NEA;
vid add Edge (NFA nta, t sBart, int end, char transiti)
hfa-> edges Lnta->edgeleunt ), start = siart;
nfa -> edges (nta -> edge lountJ. end end;
nfa -> edges [nta> edse Caunt]. trans ition- fransition;
nta -> edgo leutt+;

NEA regexTo NEA lchar *regex) {


NEA nta,
nfa. edgeCount = 0;
int state = 0;

M.M.M. UNIVERSITY OF TECHNOLOGY, GKP.


Endr a reglar expression: (atb)* a

h - b--> 2

y2
73--a-->
-> 44
TUTORIAL/ PRACTICAL NO.
for (int i- , ic strlen(ieye); itt){

addédge (&nta, state, state tI, reyexli)),


state +t',
}else if (regexliJ-*)
addE dye (& nfa, state, state t,''):
add Edge (anta, state +1,state, 'c');
state t t+,

retun nfa,

void printNFANEA nfa)


tur Cint i- o, i<nta,edzeCoun, itt){
printf ("yd-- c ->d \n", nfa.edges Ci).st art,
nta,edges). transition, nfa, edgei]. end);

char regex (MAX],


print t("Enter a reyul3r expressien : ");
scant (" s", regex),
NEA nta -rgex ToNErye ),
pnntNA (nfa);
retum o)

M.M.M. UNIVERSITY OF TECHNOLOGY, GKP. 4


TUTORIAL/ PRACTICAL NO. 3

EXPERIMENT 3
bjective Write a C prognm to Compute FIRST and
FoLLoW of the non- terminals of given
rammar,

ioram
ttincile <stdio.h>
4*inclde <stdib,h
#indude í string.h>
t de fine MAX 10
t define MAX fROD 20
# define MAX- SYMBoL 20
char prvductin s [MAXPRODI[MAX_ SYMBOLI;
char first CMAX] [MAx. SYM BoL3
*har follow [MAX] CMAX SYMBOLJ,
char nonTerminals CMAX];
int n
void compte First0;
Vid cempute Follow();
int isTerminal (char c);
int isInolow (ch c,jt index),
Vbid nddTo First(char nanTerminal, char ymbol);
vojd addTo follow (char non Terminal, chir symbo)
int main C)i
phntt(Evter the niumbtr of poductibns. )
SCanf ( 7A , Xn);
printf ("Enter the prodactions (e-g EA6); \n"');
forlint i- 0} i<n,it+)f

M.M.M. UNIVERSITY OFTECHNOLOGY, GKP.


TUTORIAL/ PRACTICAL NO.
scanf (% s, produci [iJ)
l/Extract no- terminals
if (strchr (non Termnals,
prodycions [iJ[oJ)){
nonTer minals [strlen (hantermina)] =
prvduchaliJEo.
/ Lnitialize FlRST and FoLLOW sets
tor(int i=0) /<MAX; itt){

fullow [i[o]
Compute rst);
Compute followi);
/Display HRST sets
printt ("\n FIRST set\n");
for (int i-0, ic strlen (enTer mina),
itt){
printf ("FIRST (%.c) = {", nonlermin als
(0):
for (int i-0; fivst liJLj) |=\o';
pintf(.e, firstJC;]);
itt){
printt("} \n'');
IDi splay FoLLoW sets
printt"\nfoLeow setsn'):
tor (int i: C; ickten{nonTermina); itt){
pritf( FoLLoW (l.e)- ", nanTermnals LiJ):
for int 4- 0, follow (iJlj) |= '\o'; t+) {
printf("7.e", foll owfiJG);
printf (3\n"),
return 0,

M.M.M. UNIVERSITY OF TECHNOL0GY, GKP. 6


TUTORIAL/ PRACTICAL N0.
vold Cemputefirstl){
for Cint is 0; in; it+) {
char Ihs =
productions[iJLoJ;
fer (int =3; poduciens Li) L;) |=
"lo; tt){
char synbo = pductins (iVG);
iF (isTerminal
(symhl))f
addToFirst
bveak,
(lhs, synbeld,
/Add epsiln loqic and other non-termin here
/for simplicity, asSume nm-termuinals cadri ve
0terminal diredy
/More complex losic needed for fhll implnentatia
if(isInfirst(symbol,
non Terminals)) 4
strchr (nonTer minaly syahl)
for (int k 0; fist[shrchr (nan Terminalmbo)
- nonTerminad]Lk] /= \o'; ktt){
add Tofirst (ihs frst[strehr
,Symbu) - nanleminali ]k))
(nglermnads

void Computefollow()
for (int i 0, i< str len Cnen Ter
minals), itt) {
addTo follodoTer minals (i3, $))
7 the end marker
/Assuming $ is
fur (int i: 0; i<n; itt)
for (int j-3, pro ductins (Jlj] (= \o'; t+){
if (isTerminal Cproductionsl;1))
continue ,
M.M.M. UNIVI OF TECHNOLOGY, GKP. 7
TUTORIALI PRACTICAL NO.
char namTerminl =
if (productions productieslilly,
CLi+1] |= 1o')1
char nextSymbol = produ ctien i)Gt);
if(isTerminai (next Sywmbot)
dddTofollow(nonerinal, next Synbot);
tor (int k=0; first
(strchr(nonTermina,nextymbo)
han Terminaly][k] |= \0'; ktt){
add Tofollow(nonlerminal, first[strch
hon[erminals, next symbet )- nonlerm)

I/Randle cases where non- terminal is at the


if (producions Li3 L0] (= non Terminal)4
add Tofollow(honterminal, podu chions lo

int isLnfollow(char c, ind inder)


fur (int i-0; follow LindexL3 == '\o' itt){
¡f (folow Cindex] i3== c){

return 0,

oid addTo First(char non ermina, char symbod)4


Termina)
int index = strchr (hnenTer minal, nan
hentermin
if (isIn first (symbot, index) 4
ist Cindsx](strlen (irstlinex1)] = Symbel,
Sirst Cindex] [strlen (hirstlindex])] \o

M.M.M.UNIVERSITY OF TECHNOL0GY, GKP.


Qutput
Enter the no. of produetions: 3
fnler the prodution
S’AB

fiRST setii

FRSTs) = 4a, b, e}

fIRSTCD) = b, }
CoLLoN sets .

foLLow(A) = 4b,s)
foLLOwCe) = $}
TUTORIAL/ PRACTICAL NO.
adTofo llow (chr nonlerminal, char
ind index = strchr (nonTermi als nomTeinal
nonTermina
ifCisn follow (symbot, index)){
follow Cinderylstrlen(folow Cindex3)]= sybot,
follow lindex}[stlen(fullow Lindex])] = \o';

M.M.M. UNIVERSITY OF TECHNOLOGY, GKP.


TUTORIAL/
PRACTICAL NO. 4

EXPERIMENT4
bectie Wnte a CCProgramn to check tho jiven yrammar
s Let reursive nd remOve Left recusion.

tinclude <stdio.h>
+ incude ístdibh

t defne SiZE 100


void remoneLef+ Recusion (char * grammar)
char non Terminal = Sammar loJ,
char alpha [sizEJ, beta lsIZEJ;
nt i= 3, -0 ke0,
if (nonTerminal== _rammar li) {

while (qwammarls|= | AR gramnnar liJ- '\o')


alpha ljtt} grammar itt),
lphaly] -'\o';
it(gromnar C i ] )

wtile (Yamnar liJ: o')4


beta Lk4t] 9vommor Litt]:

(" Gramar w'hont left


printf ( .c’s'hc\n", nonlerminal, bela
hon ermni nal)
Pintf(2.c-sLel\n ,nanlerminal
alpha, nonTermi nal):

UNIVERSITY OF TECHNOLOGY, GKP.


M.M.M.
Otput
Ener he roductian (eg. tE1A) A’ Aalb

A aA|e
TUTORIAL/ PRACTICAL NO.
pnntf( Thu 9tamna can't be redued n ,

pnntfe" Ti g1ammar hit t recusjwln)

char
9ramnar (si2EJ,
fnntf( Enter the production (e, E»EIA) ");
Scanf('s" ammar)
emane Lett Recusien (grammar,
retm 0)

M.M.M. UNIVERSITY OF TECHNOLOGY, GKP.


utpt
Enter a striny to check rahul lo6 @gmal.com
Matehedi ema addres
Enter a string to chect -62

Matehed: Lrteger Number


TUTORIAL/PRACTICAL NO. 5

EXPERIMENT
obiectiwi Write a
5 the
Pregram uaing lex to implement
the
set of regular expresien and indicates
acceptane of a gven string for a particuar regar
presin,

include <stdio, h>


De initiens ot regular expresins t/
La-zA-209_]+@la-zA-20-9]+\.
CAddressn");}/ azA-Z]{e, Aprintf"Matehed: Email
Matches string of the form [email protected]
-+]?Co-9]+ {printf("Mutehed:Intesr
Motehes Atings hat Tember\n");/I Integer Nunbers
are
-0?C0 -5]+\.[o-s)+ fprintf ("Matched Aoatngposi ive nagative integers A,ete
foint
-ZA-Z3+ /Nunbers: Matehes sting ihe 3.4, mberin/Plotin
-.S
point
Bprintf(Matehod?
haracters Alphabetic
(a-zA-2] +) String n"'3tMatehes olghaktic
{/*1gnore newines /}
printt("No mateh found for: sn
9y text)! }
int main)t
printf ("Euter shring to hack:\n");
ylex);
rtun 0)
nt yy rap){
return L,

M.M. UNVERSITY OF TECHNOLOGY, GKP.

You might also like