CD Lab Manual
CD Lab Manual
Source code:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' || (str[i] == '-' && i > 0))
return (false);
}
return (true);
}
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'
&& str[i] != '3' && str[i] != '4' && str[i] != '5'
&& str[i] != '6' && str[i] != '7' && str[i] != '8'
&& str[i] != '9' && str[i] != '.' ||
(str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true;
}
return (hasDecimal);
}
right++;
left = right;
} else if (isDelimiter(str[right]) == true && left != right
|| (right == len && left != right)) {
char* subStr = subString(str, left, right - 1);
if (isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr);
// DRIVER FUNCTION
int main()
{
// maximum length of string is 100 here
char str[100] = "int a = b + 1c; ";
return (0);
}
Output:
'int' IS A KEYWORD
'a' IS A VALID IDENTIFIER
'=' IS AN OPERATOR
'b' IS A VALID IDENTIFIER
'+' IS AN OPERATOR
'1c' IS NOT A VALID IDENTIFIER
Experiment-2
Write a Lex Program to implement a Lexical Analyzer
using Lex tool.
Source code:
%{
int line_num = 1;
%}
%x COMMENT
%%
"//".* /* ignore single line comments */
"/*" { BEGIN(COMMENT); }
"*/" { BEGIN(INITIAL); }
"if" { printf("IF at line %d\n", line_num); }
"else" { printf("ELSE at line %d\n", line_num); }
"for" { printf("FOR at line %d\n", line_num); }
"int" { printf("INT at line %d\n", line_num); }
"return" { printf("RETURN at line %d\n", line_num); }
"+" { printf("PLUS at line %d\n", line_num); }
"-" { printf("MINUS at line %d\n", line_num); }
"*" { printf("TIMES at line %d\n", line_num); }
"/" { printf("DIVIDE at line %d\n", line_num); }
"(" { printf("LEFT_PAREN at line %d\n", line_num); }
")" { printf("RIGHT_PAREN at line %d\n", line_num); }
"{" { printf("LEFT_BRACE at line %d\n", line_num); }
"}" { printf("RIGHT_BRACE at line %d\n", line_num); }
";" { printf("SEMICOLON at line %d\n", line_num); }
[ \t\n]+ { line_num++; }
[0-9]+ { printf("NUMBER at line %d\n", line_num); }
[a-zA-Z]+ { printf("IDENTIFIER at line %d\n", line_num); }
. { printf("INVALID CHARACTER at line %d\n", line_num); }
%%
int main(int argc, char* argv[]) {
yylex();
return 0;
}
int yywrap() {
return 1;
}
Output:
>>lex ex2.l
>>gcc lex.yy.c -o ex2
>>./ex2 < new.c
INVALID CHARACTER at line 1
IDENTIFIER at line 1
INVALID CHARACTER at line 2
IDENTIFIER at line 2
INVALID CHARACTER at line 2
IDENTIFIER at line 2
INVALID CHARACTER at line 2
INT at line 3
IDENTIFIER at line 4
LEFT_PAREN at line 4
RIGHT_PAREN at line 4
LEFT_BRACE at line 4
IDENTIFIER at line 5
LEFT_PAREN at line 5
INVALID CHARACTER at line 5
IDENTIFIER at line 5
INVALID CHARACTER at line 5
IDENTIFIER at line 5
INVALID CHARACTER at line 5
RIGHT_PAREN at line 5
SEMICOLON at line 5
RIGHT_BRACE at line 6
Experiment-3
Write a C program to Simulate Lexical Analyzer to
validating a given input String
Source code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isKeyword(char *token) {
char keywords[32][10] = { "auto", "break", "case", "char", "const",
"continue", "default",
"do", "double", "else", "enum", "extern",
"float", "for", "goto",
"if", "int", "long", "register", "return",
"short", "signed",
"sizeof", "static", "struct", "switch",
"typedef", "union",
"unsigned", "void", "volatile", "while" };
int i;
for (i = 0; i < 32; ++i) {
if (strcmp(keywords[i], token) == 0) {
return 1;
}
}
return 0;
}
int main() {
char input[100], *token;
printf("Enter an input string: ");
fgets(input, sizeof(input), stdin);
Output:
Enter an input string: for i in j
for is a keyword
i is an identifier
in is an identifier
j is an identifier
Experiment-4
Write a C program to implement the Brute force technique of Top
down Parsing
Source code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char input[100];
int position = 0;
int error = 0;
void E();
void T();
void F();
void T() {
F();
while(input[position] == '*' || input[position] == '/') {
position++;
F();
}
}
void F() {
if(isdigit(input[position]))
position++;
else if(input[position] == '(') {
position++;
E();
if(input[position] == ')')
position++;
else
error = 1;
}
else
error = 1;
}
void E() {
T();
while(input[position] == '+' || input[position] == '-') {
position++;
T();
}
}
int main() {
printf("Enter an expression: ");
scanf("%s", input);
E();
if(position == strlen(input) && error == 0)
printf("\nExpression is valid\n");
else
printf("\nExpression is invalid\n");
return 0;
}
Output:
Enter an expression: 2+3
Expression is valid
Experiment-5
Write a C program to implement a Recursive Descent Parser.
Source code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int position = 0;
char input[100];
int E();
int T();
int Ep();
int Tp();
int F();
int E() {
int result = T();
result = Ep(result);
return result;
}
int T() {
int result = F();
result = Tp(result);
return result;
}
int F() {
if (isdigit(input[position])) {
int result = input[position] - '0';
position++;
return result;
} else if (input[position] == '(') {
position++;
int result = E();
if (input[position] == ')') {
position++;
return result;
} else {
printf("Error: Missing ')'\n");
return -1;
}
} else {
printf("Error: Invalid token\n");
return -1;
}
}
int main() {
printf("Enter an input string: ");
scanf("%s", input);
return 0;
}
Output:
Enter an input string: 2+1
Valid input, result = 3
Experiment-6
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char non_terminals[] = "E";
char terminals[] = "i+";
char productions[][10] = {"E->E+i", "E->i"};
int n = 1, m = 2;
int first[10];
int follow[10];
void first_set(int i) {
int j;
if (!isupper(productions[i][2])) {
first[i] = productions[i][2];
} else {
int k = productions[i][2] - 'A';
first_set(k);
first[i] = first[k];
}
}
void follow_set(int i) {
if (productions[i][0] == 'E' && productions[i][3] == 0)
follow[i] = '$';
for (int j = 0; j < n; j++) {
for (int k = 2; productions[j][k]; k++) {
if (productions[j][k] == productions[i][0]) {
if (productions[j][k + 1] != 0) {
if (!isupper(productions[j][k + 1]))
follow[i] = productions[j][k + 1];
else {
int l = productions[j][k + 1] - 'A';
first_set(l);
follow[i] = first[l];
}
} else
follow_set(j);
}
}
}
}
int main() {
for (int i = 0; i < n; i++) {
first_set(i);
printf("First(%c) = { ", non_terminals[i]);
for (int j = 0; j < m; j++)
if (first[i] == terminals[j])
printf("%c }\n", terminals[j]);
}
for (int i = 0; i < n; i++) {
follow_set(i);
printf("Follow(%c) = { ", non_terminals[i]);
for (int j = 0; j < m; j++)
if (follow[i] == terminals[j])
printf("%c }\n", terminals[j]);
}
return 0;
}
Output:
First(E) = { Follow(E) = { + }
Experiment-7
Write a C program for eliminating the left recursion and left factoring of a
given grammar
Source code:
#include <stdio.h>
#include <string.h>
#define MAX_PRODUCTIONS 20
#define MAX_SYMBOLS 20
int main() {
char productions[MAX_PRODUCTIONS][MAX_SYMBOLS];
int n;
int i, j, k, l, m;
int flag = 0;
printf("Enter the number of productions: ");
scanf("%d", &n);
printf("Enter the productions (A -> B) :\n");
// Left Factoring
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
for (k = 2; productions[j][k]; k++) {
for (l = 2; productions[i][l]; l++) {
if (productions[i][l] == productions[j][k]) {
flag = 1;
break;
}
}
if (flag == 1) {
break;
}
}
if (flag == 1) {
m = strlen(productions[j]);
productions[j][m + 2] = productions[i][0];
productions[j][m + 3] = '\0';
}
}
}
return 0;
}
Output:
Enter the number of productions: 1
Enter the productions (A -> B) :
E -> TE'
Experiment-8
Write a C program to check the validity of input string using Predictive
Parser.
Source code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char productions[10][10];
char stack[20];
int top = -1, n = 0;
char pop()
{
return stack[top--];
}
int main()
{
int i, j, l;
char input[20], item;
printf("Enter the number of productions: ");
scanf("%d", &n);
printf("Enter the productions: \n");
for (i = 0; i < n; i++)
{
scanf("%s", productions[i]);
}
printf("Enter the input string: ");
scanf("%s", input);
l = strlen(input);
item = productions[0][0];
push(item);
i = 0;
printf("Stack\t\tInput\t\tAction\n");
while (i < l)
{
printf("%s\t\t%s\t\t", stack, input + i);
item = pop();
if (isupper(item))
{
int index = get_index(item);
if (index == -1)
{
printf("Invalid\n");
return 0;
}
else
{
int k = 2;
while (productions[index][k] != '\0')
{
push(productions[index][k++]);
}
printf("Reduced %c -> %s\n", item, productions[index] + 2);
}
}
else
{
if (item == input[i])
{
i++;
printf("Match\n");
}
else
{
printf("Invalid\n");
return 0;
}
}
}
if (stack[top] == '$' && i == l)
{
printf("Valid\n");
}
else
{
printf("Invalid\n");
}
return 0;
}
Output:
Enter the number of productions: 1
Enter the productions:
E' -> +TE' | ε
Enter the input string: Stack Input Action
E -> Reduced E ->
E -> Invalid
Experiment-9
Write a C program for implementation of LR parsing algorithm to accept a
given input string.
Source code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char stack[MAX];
int top = -1;
void push(char c) {
stack[++top] = c;
}
char pop() {
return stack[top--];
}
char peek() {
return stack[top];
}
int is_operator(char c) {
if (c == '+' || c == '-' || c == '*' || c == '/') {
return TRUE;
}
return FALSE;
}
int precedence(char c) {
if (c == '+' || c == '-') {
return 1;
} else if (c == '*' || c == '/') {
return 2;
}
return -1;
}
postfix[j] = '\0';
}
int main() {
char infix[] = "a+b*c";
char postfix[MAX];
infix_to_postfix(infix, postfix);
printf("Infix: %s\n", infix);
printf("Postfix: %s\n", postfix);
return 0;
}
Output:
Infix: a+b*c
Postfix: abc*+
Experiment-10
Write a C program for implementation of a Shift Reduce Parser using Stack
Data Structure to accept a given input string of a given grammar.
Source Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 50
char stack[MAX];
int top = -1;
void push(char item)
{
if (top >= MAX - 1)
{
printf("Stack Overflow\n");
exit(1);
}
else
{
top = top + 1;
stack[top] = item;
}
}
char pop()
{
if (top < 0)
{
printf("Stack Underflow\n");
exit(1);
}
else
{
char item = stack[top];
top = top - 1;
return item;
}
}
int precedence(char symbol)
{
switch (symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '(':
case ')':
return 1;
case '^':
return 3;
}
return -1;
}
void reduce(char *input)
{
int i, length;
char item, x;
length = strlen(input);
input[++length] = ')';
push('(');
for (i = 0; i < length; i++)
{
item = input[i];
if (item == '(')
push(item);
else if (isalnum(item))
{
printf("%c", item);
}
else if (item == ')')
{
x = pop();
while (x != '(')
{
printf("%c", x);
x = pop();
}
}
else
{
while (precedence(stack[top]) >= precedence(item))
{
printf("%c", pop());
}
push(item);
}
}
while (stack[top] != '(')
{
printf("%c", pop());
}
}
int main()
{
char input[50];
printf("Enter the expression : ");
scanf("%s", input);
reduce(input);
return 0;
}
Output:
Enter the expression : a+b*c
abc*+(Stack Underflow
Experiment-11
%token NUM
%left '-' '+'
%left '*' '/'
%right '^'
%%
input:
| input line
;
line:
| expression '\n' { printf("\t%.10g\n", $1); }
| error '\n' { yyerrok; }
;
expression:
| NUM { $$ = $1; }
| expression '+' expression { $$ = $1 + $3; }
| expression '-' expression { $$ = $1 - $3; }
| expression '*' expression { $$ = $1 * $3; }
| expression '/' expression { $$ = $1 / $3; }
| '(' expression ')' { $$ = $2; }
| '-' expression %prec '^' { $$ = -$2; }
| expression '^' expression { $$ = pow($1, $3); }
;
%%
#include<ctype.h>
#include<stdio.h>
#include<string.h>
int yylex(void) {
int c;
while ((c = getchar()) == ' ' || c == '\t');
if (c == '.' || isdigit(c)) {
ungetc(c, stdin);
scanf("%lf", &yylval);
return NUM;
}
if (c == EOF) return 0;
return c;
}
int main(void) {
return yyparse();
}
Output:
>>lex calculator.l
>>yacc -d calculator.y
>>gcc lex.yy.c y.tab.c -o calculator -lm
>>./calculator
>>2 + 3
5
Experiment-12
Generate YACC specification for a few syntactic categories.
Source code:
%{
#include <stdio.h>
#include <ctype.h>
#include <math.h>
double yylval;
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
input: /* empty */
| input line
;
line: '\n'
| expression '\n' { printf("%g\n", $1); }
;
%%
int yywrap(void) {
return 1;
}
int main(void) {
return yyparse();
}
Output:
enter input string
hello
stack input action
$h ello$ SHIFT->symbols
$he llo$ SHIFT->symbols
$hel lo$ SHIFT->symbols
$hell o$ SHIFT->symbols
$hello $ SHIFT->symbols
Experiment-13
Write a C program for generating the three address code of a given
expression/statement.
Source Code:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
void push(char c)
{
stack[++tos]=c;
}
char pop()
{
return stack[tos--];
}
int main()
{
char infix[20];
int i, j=0;
while(tos!=-1)
generateCode(id[j++], id[j-2], id[j-1]);
return 0;
}
Output:
Enter the infix expression : a + b * c
Experiment-14
Write a C program for implementation of a Code Generation Algorithm of a
given expression/statement.
Source Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int tempCount = 0;
char* newtemp() {
char* temp = (char*)malloc(10 * sizeof(char));
sprintf(temp, "t%d", tempCount++);
return temp;
}
int main() {
char *arg1 = "2", *arg2 = "3";
char op = '+';
char result[10];
codeGen(result, arg1, &op, arg2);
printf("Result: %s\n", result);
return 0;
}
Output:
t0 = 2 + 3
Result: t0