0% found this document useful (0 votes)
11 views67 pages

CD Manual

Lab manual
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)
11 views67 pages

CD Manual

Lab manual
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/ 67

JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

JECRC Campus, Shri Ram Ki Nangal, Via-Vatika, Jaipur

LAB MANUAL

Lab Name : COMPILER DESIGN LAB

Lab Code : 5CS4-22

Branch : Computer Science & Engineering

Year : 2021-22

Department of Computer Science & Engineering


Jaipur Engineering College and Research Centre, Jaipur
(Affiliated to RTU, Kota)
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

JECRC Campus, Shri Ram Ki Nangal, Via-Vatika, Jaipur

INDEX

S. No. Contents Page


No.
1 Vision and Mission of the Institute iv
2 Vision and Mission of the Department v
3 Program Educational Objectives (PEOs) vi
4 Program Outcomes (POs) vii
5 PSO of the Department (PSOs) viii
6 RTU Syllabus with List of Experiments ix-x
7 Course Outcomes (COs) xi-xii
8 CO/PO-PSO mapping xiii
9 Introduction about Lab & its Applications xiv
10 Instructions Sheet xv
Experiment List (As per RTU, Kota Syllabus)
Experiment 1 Objective: - Introduction: Objective, scope and outcome of the course. 15
Experiment 2 Objective: - To identify whether given string is keyword or not. 16
Experiment 3 Objective:-Count total no. of keywords in a file. [Taking file from 19
user]
23
Experiment 4
Objective: - Count total no of operators in a file. [Taking file from
user]

Experiment 5 Objective: - Count total occurrence of each character in a given file. 24

Objective: Write a C program to insert, delete and display the entries 26


Experiment 6
in Symbol Table

Experiment 7 Objective: - Write a LEX program to identify following: 32


1. Valid mobile number
2. Valid url
3. Valid identifier
4. Valid date (dd/mm/yyyy)
5. Valid time (hh:mm:ss)

Experiment 8 Objective: - Write a lex program to count blank spaces, words, lines in 38
a given file.
JAIPUR ENGINEERING COLLEGE AND RESEARCH CENTRE

JECRC Campus, Shri Ram Ki Nangal, Via-Vatika, Jaipur

41
Experiment 9 Objective: - Write a lex program to count the no. of vowels and
consonants in a C file.

Experiment 10 Objective: -Write a YACC program to recognize strings aaab, abbb


42
using a^nb^n, where b>=0.

Experiment 11 Objective: Write a YACC program to evaluate an arithmetic 44


expression involving operators +,-,* and /.
Objective: - Write a YACC program to recognize string with grammar 47
Experiment 12 a^n b^n, n>=0

Experiment 13 Objective: - Write a C program to find first of any grammar. 50

Content Beyond Syllabus


Objective: Implement the lexical analyser using JLex, flex or 67
Experiment 14
other lexical analyser generating tools
Objective: Implement Predictive Parser for the given language 69
Experiment 15
Objective: Implement a LALR bottom up parser for the given 72
Experiment 16
language
Vision of the Institute

To become a renowned centre of outcome based learning, and work towards academic,
professional, cultural and social enrichment of the lives of individuals and communities.

Mission of the Institute

M1: Focus on evaluation of learning outcomes and motivate students to inculcate research
aptitude by project based learning.

M2: Identify, based on informed perception of Indian, regional and global needs, areas of focus
and provide platform to gain knowledge and solutions.

M3: Offer opportunities for interaction between academia and industry.

M4: Develop human potential to its fullest extent so that intellectually capable and
imaginatively gifted leaders can emerge in a range of professions.
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Vision of the Department


To become renowned Centre of excellence in computer science and engineering and
make competent engineers & professionals with high ethical values prepared for
lifelong learning.

Mission of the Department


M1- To impart outcome based education for emerging technologies in the field of
computer science and engineering.
M2 - To provide opportunities for interaction between academia and industry.
M3 - To provide platform for lifelong learning by accepting the change in technologies
M4 - To develop aptitude of fulfilling social responsibilities.

5|Page
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

1. To provide students with the fundamentals of Engineering Sciences with more


emphasis in Mechanical Engineering by way of analyzing and exploiting engineering
challenges.
2. To train students with good scientific and engineering knowledge so as to comprehend,
analyze, design, and create novel products and solutions for the real life problems.
3. To inculcate professional and ethical attitude, effective communication skills,
teamwork skills, multidisciplinary approach, entrepreneurial thinking and an ability to
relate engineering issues with social issues.
4. To provide students with an academic environment aware of excellence, leadership,
written ethical codes and guidelines, and the self-motivated life-long learning needed
for a successful professional career.
5. To prepare students to excel in Industry and Higher education by Educating Students
along with High moral values and Knowledge.

6|Page
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

PROGRAM OUTCOMES (POs)


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10.Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

7|Page
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1: Ability to interpret and analyze network specific and cyber security issues in
real world environment.
PSO2: Ability to design and develop mobile and web based application under
realistic constraints.

. RTU Syllabus with List of Experiments

5CS4-22: COMPUTER DESIGN LAB

8|Page
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Course Outcomes
CO1. Apply the concept of Lexical Analyzer using C/C++ and FLEX tool
CO2. Analyze different types of parsing and allocation data structure

Mapping of Experiments with Cos & BT Level

Experiment CO’s BT
Objective
No.

Objective: - To identify whether given string is 3


Exp:- 1 CO1
keyword or not.
Exp:-2 Objective:-Count total no. of keywords CO1 3
in a file. [Taking file from user]
3
Exp:-3 Objective: - Count total no of operators in a file. CO1
[Taking file from user]
Objective: - Count total occurrence of each 3
CO1
Exp:-4 character in a given file.

Objective: Write a C program to insert, delete and 3


CO2
Exp:-5 display the entries in Symbol Table

Objective: - Write a LEX program to identify 4


following:
1. Valid mobile number
2. Valid url CO1
3. Valid identifier
4. Valid date (dd/mm/yyyy)
Exp:-6
5. Valid time (hh:mm:ss)
Exp:-7 Objective: - Write a lex program to count blank CO1 4
spaces, words, lines in a given file.

9|Page
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Exp:-8 4
Objective: - Write a lex program to count the no. of CO1
vowels and consonants in a C file.
Objective: -Write a YACC program to recognize 4
Exp:-9 CO2
strings aaab, abbb using a^nb^n, where b>=0.
Objective: Write a YACC program to evaluate an 5
Exp:10 arithmetic expression involving operators +,-,* and CO2
/.
Exp:11 Objective: - Write a YACC program to recognize CO2 4
string with grammar a^n b^n, n>=0
Objective: - Write a C program to find first of any 4
CO2
Exp:12 grammar.

* BT - Bloom's Taxonomy

MAPPING OF CO & PO

COURSE PROGRAM OUTCOMES


OUTCOMES
1 2 3 4 5 6 7 8 9 10 11 12

I 3 3 3 2 3 - - - 1 1 2 2

II 3 3 3 2 2 - - - 1 1 2 2

10 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

INTRODUCTION ABOUT LABORATORY & APPLICATIONS

Compiler is a software which takes as input a program written in a High-Level language and
translates it into its equivalent program in Low Level program. Compilers teaches us how real-
world applications are working and how to design them. Learning Compilers gives us with
both theoretical and practical knowledge that is crucial in order to implement a programming
language. It gives you a new level of understanding of a language in order to make better use
of the language (optimization is just one example). Sometimes just using a compiler is not
enough. You need to optimize the compiler itself for your application. Compilers have a
general structure that can be applied in many other applications, from debuggers to simulators
to 3D applications to a browser and even a cmd / shell. understanding compilers and how they
work makes it super simple to understand all the rest. a bit like a deep understanding of math
will help you to understand geometry or physics. We cannot do physics without the math. not
on the same level. Just using something (read: tool, device, software, programming language)
is usually enough when everything goes as expected. But if something goes wrong, only a true
understanding of the inner workings and details will help to fix it. Even more specifically,
Compilers are super elaborated / sophisticated systems (architecturally speaking). If you will
say that can or have written a compiler by yourself - there will be no doubt as to your
capabilities as a programmer. There is nothing you cannot do in the Software realm. So, better
be a pilot who have the knowledge and mechanics of an airplane than the one who just know
how to fly. Every computer scientist can do much better if have knowledge of compilers apart
from the domain and technical knowledge. Compiler design lab provides deep understanding
of how programming language Syntax, Semantics are used in translation into machine
equivalents apart from the knowledge of various compiler generation tools like LEX,YACC
etc.

11 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

INSTRUCTIONS OF LAB

1.1.1.1 DO’s
1. Please switch off the Mobile/Cell phone before entering Lab.
2. Enter the Lab with complete source code and data.
3. Check whether all peripheral are available at your desktop before proceeding for
program.
4. Intimate the lab in charge whenever you are incompatible in using the system or
in case software get corrupted/ infected by virus.
5. Arrange all the peripheral and seats before leaving the lab.
6. Properly shutdown the system before leaving the lab.
7. Keep the bag outside in the racks.
8. Enter the lab on time and leave at proper time.
9. Maintain the decorum of the lab.
10. Utilize lab hours in the corresponding experiment.
11. Get your CD / Pen drive checked by lab in charge before using it in the lab.

1.1.1.2 DON’TS
1. No one is allowed to bring storage devices like Pan Drive /Floppy etc. in the
lab.
2. Don’t mishandle the system.
3. Don’t leave the system on standing for long
4. Don’t bring any external material in the lab.
5. Don’t make noise in the lab.
6. Don’t bring the mobile in the lab. If extremely necessary then keep ringers off.
7. Don’t enter in the lab without permission of lab in charge.
8. Don’t litter in the lab.
12 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

9. Don’t delete or make any modification in system files.


10. Don’t carry any lab equipment’s outside the lab.

INSTRUCTIONS FOR STUDENT

BEFORE ENTERING IN THE LAB


 All the students are supposed to prepare the theory regarding the next program.
 Students are supposed to bring the practical file and the lab copy.
 Previous programs should be written in the practical file.
 Any student not following these instructions will be denied entry in the lab.

2 WHILE WORKING IN THE LAB

 Adhere to experimental schedule as instructed by the lab in charge.


 Get the previously executed program signed by the instructor.
 Get the output of the current program checked by the instructor in the lab copy.
 Each student should work on his/her assigned computer at each turn of the lab.
 Take responsibility of valuable accessories.
 Concentrate on the assigned practical and do not play games.

13 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No.1
Aim: - Introduction: Objective, scope and outcome of the course.

14 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 2
Aim: To identify whether given string is keyword or not.
Source Code:-

01 #include<stdio.h>
02
03 #include<conio.h>
04
05 #include<string.h>
06
07 void main()
08
09 {

15 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

10
11 char keyword[32][10]={"auto","double","int","struct","break","else","long",
12
13 "switch","case","enum","register","typedef","char",
14
15 "extern","return","union","const","float","short",
16
17 "unsigned","continue","for","signed","void","default",
18
19 "goto","sizeof","voltile","do","if","static","while"} ;
20
21 char string[10];
22
23 int flag=0,i;
24
25 printf("enter any string:");
26
27 gets(string);
28
29 for(i=0;i<32;i++)
30
31 {
32
33 if(strcmp(string,keyword[i])==0)
34
35 {
36
37 flag=1;
38
39 }
40

16 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

41
42
43 }
44
45
46
47 if(flag==1)
48
49 printf("%s is a keyword",string);
50
51 else
52
53 printf("%s is not a keyword",string);
54
55
56
57 getch();
58
59 }
Output:

17 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 3

Aim: Write a C program to count total no. of keywords in a file. [Taking file from user]
Source Code:-
1. * using Array Structure
2. */
3. #include <stdio.h>
4. #include <string.h>
5. #include <ctype.h>
6. #define KEYMAX 32
7.
8. struct keyword
9. {
10. char word[10];
11. int occur;
12. };
13.
14. int binarysearch(char [], struct keyword[]);
15.
16. int main()
17. {
18. int i = 0, j = 0, pos;

18 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

19. char string[100], unit[20], c;


20. struct keyword key[32] = {"auto", 0, "break", 0, "case", 0,
21. "char", 0, "const", 0, "continue", 0,
22. "default", 0, "do", 0, "double", 0,
23. "else", 0, "enum", 0, "extern", 0,
24. "float", 0, "for", 0, "goto", 0,
25. "if", 0, "int", 0, "long", 0,
26. "register", 0, "return", 0, "short", 0,
27. "signed", 0, "sizeof", 0, "static", 0,
28. "struct", 0, "switch", 0, "typedef", 0,
29. "union", 0, "unsigned", 0, "void", 0,
30. "volatile", 0, "while", 0,};
31.
32. printf("Enter string: ");
33. do
34. {
35. fflush(stdin);
36. c = getchar();
37. string[i++] = c;
38.
39. } while (c != '\n');
40. string[i - 1] = '\0';
41. printf("The string entered is: %s\n", string);
42. for (i = 0; i < strlen(string); i++)
43. {
44. while (i < strlen(string) && string[i] != ' ' && isalpha(string[i]))
45. {
19 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

46. unit[j++] = tolower(string[i++]);


47. }
48. if (j != 0)
49. {
50. unit[j] = '\0';
51. pos = binarysearch(unit, key);
52. j = 0;
53. if (pos != -1)
54. {
55. key[pos].occur++;
56. }
57. }
58. }
59. printf("***********************\n Keyword\tCount\n*****************
******\n");
60. for (i = 0; i < KEYMAX; i++)
61. {
62. if (key[i].occur)
63. {
64. printf(" %s\t %d\n", key[i].word, key[i].occur);
65. }
66. }
67.
68. return 0;
69. }
70.
71. int binarysearch(char *word, struct keyword key[])
20 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

72. {
73. int low, high, mid;
74.
75. low = 0;
76. high = KEYMAX - 1;
77. while (low <= high)
78. {
79. mid = (low + high) / 2;
80. if (strcmp(word, key[mid].word) < 0)
81. {
82. high = mid - 1;
83. }
84. else if (strcmp(word, key[mid].word) > 0)
85. {
86. low = mid + 1;
87. }
88. else
89. {
90. return mid;
91. }
92. }
93.
94. return -1;
95. }

Output :-

21 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

$ gcc keywordoccur.c
$ ./a.out
Enter string: break, float and double are c keywords. float and double are primitive data type
s. The string entered is: break, float and double are c keywords. float and double are primiti
ve data types.
***********************
Keyword Count
***********************
break 1
double 2
float 2

Experiment No.4

Aim: Write a program to count total no of operators in a file. [Taking file from user].
Source Code:-
#include<stdio.h>
#include<conio.h>
int main()
{
char s[200];
int count = 0, i;
printf(“Enter the string:\n”);
scanf(“%[^\n]s”, s)’;
for ( i = 0; s[ i ] != ‘\0’ ; i++ )
{
if ( s[ i ] = = ‘+’ | | s[ i ] = = ‘-’ | | s[ i ] = = ‘*’ | | s[ i ] = = ‘/’ | | )

22 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

count++;
}
printf(“Number of Operators in a given string are:%d\n”, count);
}

Experiment No. 5

Aim: Write a C Program to Count total occurrence of each character in a given file.
[Taking file from user]
Description: C program to find the frequency of characters in a string: This program counts
the frequency of characters in a string, i.e., which character is present how many times in the
string. For example, in the string "code" each of the characters 'c,' 'd,' 'e,' and 'o' has occurred
one time. Only lower case alphabets are considered, other characters (uppercase and special
characters) are ignored. You can easily modify this program to handle uppercase and special
symbols.

Source Code:

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char string[100];
7. int c = 0, count[26] = {0}, x;
23 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

8.
9. printf("Enter a string\n");
10. gets(string);
11.
12. while (string[c] != '\0') {
13. /** Considering characters from 'a' to 'z' only and ignoring others. */
14.
15. if (string[c] >= 'a' && string[c] <= 'z') {
16. x = string[c] - 'a';
17. count[x]++;
18. }
19.
20. c++;
21. }
22.
23. for (c = 0; c < 26; c++)
24. printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
25.
26. return 0;
27. }

Explanation of "count[string[c]-'a']++", suppose input string begins with 'a' so c is 0 initially


and string[0] = 'a' and string[0] - 'a' = 0 and we increment count[0] i.e. 'a' has occurred one time
and repeat this till the complete string is scanned.

Output:

24 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 6

Aim: Write a C program to insert, delete and display the entries in Symbol Table.

Source code:-

1. #include<stdio.h>
2. #include<conio.h>
3. #include<alloc.h>
4. #include<string.h>
5. #include<stdlib.h>
6. #define NULL 0
7. int size=0;
8. void Insert();
9. void Display();
10. void Delete();
11. int Search(char lab[]);void Modify();
12. struct SymbTab
13. {

25 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

14. char label[10],symbol[10];


15. int addr;
16. struct SymbTab *next;};
17. struct SymbTab *first,*last;
18. void main()
19. {
20. int op,y;
21. char la[10];
22. clrscr();
23. do
24. {
25. printf(“\n\tSYMBOL TABLE IMPLEMENTATION\n”);
26. printf(“\n\t1.INSERT\n\t2.DISPLAY\n\t3.DELETE\n\t4.SEARCH\n\t5.MODIFY\n\t6.END\n”
);
27. printf(“\n\tEnter your option : “);
28. scanf(“%d”,&op);
29. switch(op)
30. {
31. case 1:
32. Insert();
33. break;
34. case 2:
35. Display();
36. break;
37. case 3:
38. Delete();
39. break;
40. case 4:
41. printf(“\n\tEnter the label to be searched : “);
42. scanf(“%s”,la);
43. y=Search(la);
44. printf(“\n\tSearch Result:”);
45. if(y==1)
46. printf(“\n\tThe label is present in the symbol table\n”);
47. else
48. printf(“\n\tThe label is not present in the symbol table\n”);
49. break;
50. case 5:
51. Modify();
52. break;
26 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

53. case 6:
54. exit(0);
55. }
56. }while(op<6);
57. getch();
58. }
59. void Insert()
60. {
61. int n;
62. char l[10];
63. printf(“\n\tEnter the label : “);
64. scanf(“%s”,l);
65. n=Search(l);
66. if(n==1)
67. printf(“\n\tThe label exists already in the symbol table\n\tDuplicate can’t be inserted”);
68. else
69. {
70. struct SymbTab *p;
71. p=malloc(sizeof(struct SymbTab));
72. strcpy(p->label,l);
73. printf(“\n\tEnter the symbol : “);
74. scanf(“%s”,p->symbol);
75. printf(“\n\tEnter the address : “);
76. scanf(“%d”,&p->addr);
77. p->next=NULL;
78. if(size==0)
79. {
80. first=p;
81. last=p;
82. }
83. else
84. {
85. last->next=p;
86. last=p;
87. }
88. size++;
89. }
90. printf(“\n\tLabel inserted\n”);
91. }
92. void Display()
27 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

93. {
94. int i;
95. struct SymbTab *p;
96. p=first;
97. printf(“\n\tLABEL\t\tSYMBOL\t\tADDRESS\n”);
98. for(i=0;i<size;i++)
99. {
100. printf(“\t%s\t\t%s\t\t%d\n”,p->label,p->symbol,p->addr);
101. p=p->next;
102. }
103. }
104. int Search(char lab[])
105. {
106. int i,flag=0;
107. struct SymbTab *p;
108. p=first;
109. for(i=0;i<size;i++)
110. {
111. if(strcmp(p->label,lab)==0)
112. flag=1;
113. p=p->next;
114. }
115. return flag;
116. }
117. void Modify()
118. {
119. char l[10],nl[10];
120. int add,choice,i,s;
121. struct SymbTab *p;
122. p=first;
123. printf(“\n\tWhat do you want to modify?\n”);
124. printf(“\n\t1.Only the label\n\t2.Only the address\n\t3.Both the label and address\n”);
125. printf(“\tEnter your choice : “);
126. scanf(“%d”,&choice);
127. switch(choice)
128. {
129. case 1:
130. printf(“\n\tEnter the old label : “);
131. scanf(“%s”,l);
132. s=Search(l);
28 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

133. if(s==0)
134. printf(“\n\tLabel not found\n”);
135. else
136. {
137. printf(“\n\tEnter the new label : “);
138. scanf(“%s”,nl);
139. for(i=0;i<size;i++)
140. {
141. if(strcmp(p->label,l)==0)
142. strcpy(p->label,nl);
143. p=p->next;
144. }
145. printf(“\n\tAfter Modification:\n”);
146. Display();
147. }
148. break;
149. case 2:
150. printf(“\n\tEnter the label where the address is to be modified : “);
151. scanf(“%s”,l);
152. s=Search(l);
153. if(s==0)
154. printf(“\n\tLabel not found\n”);
155. else
156. {
157. printf(“\n\tEnter the new address : “);
158. scanf(“%d”,&add);
159. for(i=0;i<size;i++)
160. {
161. if(strcmp(p->label,l)==0)
162. p->addr=add;
163. p=p->next;
164. }
165. printf(“\n\tAfter Modification:\n”);
166. Display();
167. }
168. break;
169. case 3:
170. printf(“\n\tEnter the old label : “);
171. scanf(“%s”,l);
172. s=Search(l);
29 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

173. if(s==0)
174. printf(“\n\tLabel not found\n”);
175. else
176. {
177. printf(“\n\tEnter the new label : “);
178. scanf(“%s”,nl);
179. printf(“\n\tEnter the new address : “);
180. scanf(“%d”,&add);
181. for(i=0;i<size;i++)
182. {
183. if(strcmp(p->label,l)==0)
184. {
185. strcpy(p->label,nl);
186. p->addr=add;
187. }
188. p=p->next;
189. }
190. printf(“\n\tAfter Modification:\n”);
191. Display();
192. }
193. break;
194. }
195. }
196. void Delete()
197. {
198. int a;
199. char l[10];
200. struct SymbTab *p,*q;
201. p=first;
202. printf(“\n\tEnter the label to be deleted : “);
203. scanf(“%s”,l);
204. a=Search(l);
205. if(a==0)
206. printf(“\n\tLabel not found\n”);
207. else
208. {
209. if(strcmp(first->label,l)==0)
210. first=first->next;
211. else if(strcmp(last->label,l)==0)
212. {
30 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

213. q=p->next;
214. while(strcmp(q->label,l)!=0)
215. {
216. p=p->next;
217. q=q->next;
218. }
219. p->next=NULL;
220. last=p;
221. }
222. else
223. {
224. q=p->next;
225. while(strcmp(q->label,l)!=0)
226. {
227. p=p->next;
228. q=q->next;
229. }
230. p->next=q->next;
231. }
232. size–;
233. printf(“\n\tAfter Deletion:\n”);
234. Display();
235. }
236. }

Experiment No. 7

Aim: Write a LEX program to identify following:


1. Valid mobile number & email-id
2. Valid url
3. Valid identifier
4. Valid date (dd/mm/yyyy)
5. Valid time (hh:mm:ss)

31 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Source Code:-

1. Valid mobile number & email-id

Valid mobile number


%{
/* Definition section */
%}
/* Rule Section */
%%
[1-9][0-9]{9} {printf("\nMobile Number Valid\n");}
.+ {printf("\nMobile Number Invalid\n");}
%%
// driver code
int main()
{
printf("\nEnter Mobile Number : ");
yylex();
printf("\n");
return 0;
}

Output:
Input: 7017175023
Output: Mobile Number Valid

32 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Input: 0001112223
Output: Mobile Number Invalid

Valid mobile email-id


%
{
int flag = 0; %
}%
% [a - z.0 - 9 _] + @[a - z] + ".com" | ".in"
flag = 1; %
%
main() {
yylex();
if (flag == 1)
printf("Accepted");
else
printf("Not Accepted");
}
Output:
Input :
[email protected]
Output :
Valid
Input :
[email protected]
Output :
Not Valid
33 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

2. Valid url

%%
((http)|(ftp))s?:\/\/[a-zA-Z0-9]{2, }(\.[a-z]{2, })
+(\/[a-zA-Z0-9+=?]*)* {printf("\nURL Valid\n");}

.+ {printf("\nURL Invalid\n");}

%%
// driver program
void main()
{
printf("\nEnter URL : ");
yylex();
printf("\n");
}

Output:
Input: geeksforgeeks
Output: INVALID URL

Input: https://www.geeksforgeeks.org
Output: VALID URL

3. Valid identifier

%{

34 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

#include <stdio.h>
%
}
/ rule section % %
// regex for valid identifiers
^[a - z A - Z _][a - z A - Z 0 - 9 _] * printf("Valid Identifier");
// regex for invalid identifiers
^[^a - z A - Z _] printf("Invalid Identifier");
.;
%%
main()
{
yylex();
}

Output:

4. Valid date (dd/mm/yyyy)

%{
35 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

/* Definition section */
#include<stdio.h>
int i=0, yr=0, valid=0;
%}
/* Rule Section */
%%
([0-2][0-9]|[3][0-1])\/((0(1|3|5|7|8))|(10|12))
\/([1-2][0-9][0-9][-0-9]) {valid=1;}
([0-2][0-9]|30)\/((0(4|6|9))|11)
\/([1-2][0-9][0-9][0-9]) {valid=1;}
([0-1][0-9]|2[0-8])\/02
\/([1-2][0-9][0-9][0-9]) {valid=1;}
29\/02\/([1-2][0-9][0-9][0-9])
{ while(yytext[i]!='/')i++; i++;
while(yytext[i]!='/')i++;i++;
while(i<yyleng)yr=(10*yr)+(yytext[i++]-'0');
if(yr%4==0||(yr%100==0&&yr%400!=0))valid=1;}
%%
// driver code
main()
{
yyin=fopen("vpn.txt", "r");
yylex();
if(valid==1) printf("It is a valid date\n");
else printf("It is not a valid date\n");
}
int yywrap()
36 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

{
return 1;
}

Output:
Input: 02/05/2019
Output: It is a valid date

Input: 05/20/2019
Output: It is not a valid date

5. Valid time (hh:mm:ss)

Experiment No.8

Aim: Write a lex program to count blank spaces, words, lines in a given file.

Source Code:-

%{
#include<stdio.h>
int lc=0, sc=0, tc=0, ch=0; /*Global variables*/
%}
/*Rule Section*/
%%

37 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

\n lc++; //line counter


[ ] sc++; //space counter
\t tc++; //tab counter
. ch++; //characters counter
%%
main()
{
// The function that starts the analysis
yylex();
printf("\nNo. of lines=%d, lc);
printf("\nNo. of spaces=%d, sc);
printf("\nNo. of tabs=%d, tc);
printf("\nNo. of other characters=%d, ch);
}

38 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Output:

39 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 9

Aim: Write a lex program to count the no. of vowels and consonants in a C file.

Source Code:-
%{
int vow_count=0;
int const_count =0;
%}
%%
[aeiouAEIOU] {vow_count++;}
[a-zA-Z] {const_count++;}
%%
main(){
printf("Enter the string of vowels and consonents:");
yylex();
printf("The number of vowels are: %d\n",vow);
printf("The number of consonants are: %d\n",cons);
return 0;
}

Output:
$$ lex kk.l
$$ gcc kk.c -ll
$$ ./a.out
Enter the string of vowels and consonents
40 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

My name is Khan
The number of vowels are: 4 The number of consonants are: 8

Experiment No. 10

Aim: Write a YACC program to recognize strings aaab, abbb using a^nb^n, where
b>=0.

Source Code:-

%{
/* Definition section */
#include "y.tab.h"
%}
/* Rule Section */
%%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
. {return yytext[0];}
%%
int yywrap()
{
return 1;
}
Parser Source Code :
%{

41 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

/* Definition section */
#include<stdio.h>
#include<stdlib.h>
%}
%token A B NL
/* Rule Section */
%%
stmt: S NL { printf("valid string\n");
exit(0); }
;
S: A S B |
;
%%
int yyerror(char *msg)
{
printf("invalid string\n");
exit(0);
}
//driver code
main()
{
printf("enter the string\n");
yyparse();
}
Output:

42 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 11

Aim: Write a YACC program to evaluate an arithmetic expression involving operators


+,-,*and /

Source Code:-

%
{
/* Definition section*/
#include "y.tab.h"
extern yylval;
%
}

43 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

%%
[0 - 9]
+
{
yylval = atoi(yytext);
return NUMBER;
}
[a - zA - Z] + { return ID; }
[\t] + ;
\n { return 0; }
. { return yytext[0]; }
%%
Parser Source Code:
%{
/* Definition section */
#include
%
}
% token NUMBER ID
// setting the precedence
// and associativity of operators
% left '+' '-'
% left '*' '/'
/* Rule Section */
%
%E:T

44 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

{
printf("Result = %d\n", $$);
return 0;
}
T : T '+' T { $$ = $1 + $3; }
| T '-' T { $$ = $1 - $3; }
| T '*' T { $$ = $1 * $3; }
| T '/' T { $$ = $1 / $3; }
| '-' NUMBER { $$ = -$2; }
| '-' ID { $$ = -$2; }
| '(' T ')' { $$ = $2; }
| NUMBER { $$ = $1; }
| ID { $$ = $1; };
%%
int main()
{
printf("Enter the expression\n");
yyparse();
}
/* For printing error messages */
int yyerror(char* s)
{
printf("\nExpression is invalid\n");
}
Output:

45 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Experiment No. 12

3 Aim: Write a YACC program to recognize string with grammar a^n


b^n, n>=0

Source Code:-

YACC PART:
CODE: (gram.y)

46 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

%{
#include<stdio.h>
#include<stdlib.h>
%}
%token A B NL
%%
stmt: S NL {printf("valid string\n");
exit(0);}
;
S: A S B |
;
%%
int yyerror(char *msg)
{
printf("invalid string\n");
exit(0);
}
main()
{
printf("enter the string\n");
yyparse();
}

LEX PART:
CODE: (gram.l)
%{
47 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

#include "y.tab.h"
%}
%%
[aA] {return A;}
[bB] {return B;}
\n {return NL;}
. {return yytext[0];}
%%

OUTPUT :

yacc -d gram.y
lex gram.l
cc y.tab.c lex.yy.c -ly -ll
./a.out
enter the string
ab
valid string

./a.out
enter the string
aaabb
invalid string

./a.out
enter the string
aabb
48 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

valid string

./a.out
enter the string
a
invalid string

Experiment No. 13

Aim: Write a C program to find first of any grammar.

Description & Algorithm:-

The functions follow and follow first are both involved in the calculation of the Follow Set of
a given Non-Terminal. The follow set of the start symbol will always contain “$”. Now the
calculation of Follow falls under three broad cases:

 If a Non-Terminal on the R.H.S. of any production is followed immediately by a


Terminal then it can immediately be included in the Follow set of that Non-Terminal.
 If a Non-Terminal on the R.H.S. of any production is followed immediately by a Non-
Terminal, then the First Set of that new Non-Terminal gets included on the follow set of
our original Non-Terminal. In case encountered an epsilon i.e. ” # ” then, move on to the
next symbol in the production.
Note: “#” is never included in the Follow set of any Non-Terminal.
 If reached the end of a production while calculating follow, then the Follow set of that
non-terminal will include the Follow set of the Non-Terminal on the L.H.S. of that
production. This can easily be implemented by recursion.
Assumptions:
49 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

1. Epsilon is represented by ‘#’.


2. Productions are of the form A=B, where ‘A’ is a single Non-Terminal and ‘B’ can be any
combination of Terminals and Non- Terminals.
3. L.H.S. of the first production rule is the start symbol.
4. Grammar is not left recursive.
5. Each production of a non-terminal is entered on a different line.
6. Only Upper Case letters are Non-Terminals and everything else is a terminal.
7. Do not use ‘!’ or ‘$’ as they are reserved for special purposes.

Explanation:
Store the grammar on a 2D character array production. Find first function is for
calculating the first of any non-terminal. Calculation of first falls under two broad cases:
 If the first symbol in the R.H.S of the production is a Terminal then it can directly be
included in the first set.
 If the first symbol in the R.H.S of the production is a Non-Terminal then call the find
first function again on that Non-Terminal. To handle these cases like Recursion is the
best possible solution. Here again, if the First of the new Non-Terminal contains an
epsilon then we have to move to the next symbol of the original production which can
again be a Terminal or a Non-Terminal.
Note: For the second case it is very easy to fall prey to an INFINITE LOOP even if the code
looks perfect. So it is important to keep track of all the function calls at all times and never call
the same function again.
Below is the implementation:

Source Code:-

// C program to calculate the First and

50 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

// Follow sets of a given grammar

#include<stdio.h>

#include<ctype.h>

#include<string.h>

// Functions to calculate Follow

void followfirst(char, int, int);

void follow(char c);

// Function to calculate First

void findfirst(char, int, int);

int count, n = 0;

// Stores the final result

// of the First Sets

char calc_first[10][100];

// Stores the final result

// of the Follow Sets

char calc_follow[10][100];

int m = 0;

// Stores the production rules

51 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

char production[10][10];

char f[10], first[10];

int k;

char ck;

int e;

int main(int argc, char **argv)

int jm = 0;

int km = 0;

int i, choice;

char c, ch;

count = 8;

// The Input grammar

strcpy(production[0], "E=TR");

strcpy(production[1], "R=+TR");

strcpy(production[2], "R=#");

strcpy(production[3], "T=FY");

strcpy(production[4], "Y=*FY");

strcpy(production[5], "Y=#");

52 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

strcpy(production[6], "F=(E)");

strcpy(production[7], "F=i");

int kay;

char done[count];

int ptr = -1;

// Initializing the calc_first array

for(k = 0; k < count; k++) {

for(kay = 0; kay < 100; kay++) {

calc_first[k][kay] = '!';

int point1 = 0, point2, xxx;

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

c = production[k][0];

point2 = 0;

xxx = 0;

// Checking if First of c has

// already been calculated

53 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

for(kay = 0; kay <= ptr; kay++)

if(c == done[kay])

xxx = 1;

if (xxx == 1)

continue;

// Function call

findfirst(c, 0, 0);

ptr += 1;

// Adding c to the calculated list

done[ptr] = c;

printf("\n First(%c) = { ", c);

calc_first[point1][point2++] = c;

// Printing the First Sets of the grammar

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

int lark = 0, chk = 0;

for(lark = 0; lark < point2; lark++) {

if (first[i] == calc_first[point1][lark])

chk = 1;

54 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

break;

if(chk == 0)

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

calc_first[point1][point2++] = first[i];

printf("}\n");

jm = n;

point1++;

printf("\n");

printf("-----------------------------------------------\n\n");

char donee[count];

ptr = -1;

// Initializing the calc_follow array

55 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

for(k = 0; k < count; k++) {

for(kay = 0; kay < 100; kay++) {

calc_follow[k][kay] = '!';

point1 = 0;

int land = 0;

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

ck = production[e][0];

point2 = 0;

xxx = 0;

// Checking if Follow of ck

// has alredy been calculated

for(kay = 0; kay <= ptr; kay++)

if(ck == donee[kay])

xxx = 1;

if (xxx == 1)

continue;

56 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

land += 1;

// Function call

follow(ck);

ptr += 1;

// Adding ck to the calculated list

donee[ptr] = ck;

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

calc_follow[point1][point2++] = ck;

// Printing the Follow Sets of the grammar

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

int lark = 0, chk = 0;

for(lark = 0; lark < point2; lark++)

if (f[i] == calc_follow[point1][lark])

chk = 1;

break;

57 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

if(chk == 0)

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

calc_follow[point1][point2++] = f[i];

printf(" }\n\n");

km = m;

point1++;

void follow(char c)

int i, j;

// Adding "$" to the follow

// set of the start symbol

if(production[0][0] == c) {

f[m++] = '$';

58 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

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

for(j = 2;j < 10; j++)

if(production[i][j] == c)

if(production[i][j+1] != '\0')

// Calculate the first of the next

// Non-Terminal in the production

followfirst(production[i][j+1], i, (j+2));

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

// Calculate the follow of the Non-Terminal

// in the L.H.S. of the production

follow(production[i][0]);

59 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

void findfirst(char c, int q1, int q2)

int j;

// The case where we

// encounter a Terminal

if(!(isupper(c))) {

first[n++] = c;

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

if(production[j][0] == c)

if(production[j][2] == '#')

if(production[q1][q2] == '\0')

first[n++] = '#';

60 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

else if(production[q1][q2] != '\0'

&& (q1 != 0 || q2 != 0))

// Recursion to calculate First of New

// Non-Terminal we encounter after epsilon

findfirst(production[q1][q2], q1, (q2+1));

else

first[n++] = '#';

else if(!isupper(production[j][2]))

first[n++] = production[j][2];

else

// Recursion to calculate First of

// New Non-Terminal we encounter

// at the beginning

61 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

findfirst(production[j][2], j, 3);

void followfirst(char c, int c1, int c2)

int k;

// The case where we encounter

// a Terminal

if(!(isupper(c)))

f[m++] = c;

else

int i = 0, j = 1;

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

if(calc_first[i][0] == c)

break;

62 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

//Including the First set of the

// Non-Terminal in the Follow of

// the original query

while(calc_first[i][j] != '!')

if(calc_first[i][j] != '#')

f[m++] = calc_first[i][j];

else

if(production[c1][c2] == '\0')

// Case where we reach the

// end of a production

follow(production[c1][0]);

else

63 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

// Recursion to the next symbol

// in case we encounter a "#"

followfirst(production[c1][c2], c1, c2+1);

j++;

Output:

First(E)= { (, i, }

First(R)= { +, #, }

First(T)= { (, i, }

First(Y)= { *, #, }
First(F)= { (, i, }

-----------------------------------------------

Follow(E) = { $, ), }
Follow(R) = { $, ), }

64 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

Follow(T) = { +, $, ), }
Follow(Y) = { +, $, ), }
Follow(F) = { *, +, $, ), }

65 | P a g e
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

iv
Jaipur Engineering college and research centre, Shri Ram
ki Nangal, via Sitapura RIICO Jaipur- 302 022.

You might also like