0% found this document useful (0 votes)
23 views26 pages

CD Record

record

Uploaded by

keerthanashree02
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)
23 views26 pages

CD Record

record

Uploaded by

keerthanashree02
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/ 26

1 .

lex program for counting words


%{

#include <stdio.h>

int word_count = 0;

%}

%%

[A-Za-z]+ { word_count++; }

. { /* Ignore other characters */ }

%%

int main() {

yylex();

printf("Number of words: %d\n", word_count);

return 0;

int yywrap() {

return 1;

Output:

hello world

Number of words: 2
2. lex program to count digits and words
%{

#include <stdio.h>

%}

%%

[0-9]+ { printf("Found a number: %s\n", yytext); }

[A-Za-z]+ { printf("Found a word: %s\n", yytext); }

. { /* Ignore other characters */ }

%%

int main() {

yylex();

return 0;

int yywrap() {

return 1;

Output: my rollnumber is 21N71A0570

Found a word: my

Found a word: rollnumber

Found a word: is

Found a number: 21

Found a word: N

Found a number: 71

Found a word: A

Found a number: 0570


3. lex program to implement simple calculator
%{

#include <stdio.h>

#include <stdlib.h>

int op = 0,i;

float a, b;

%}

dig [0-9]+|([0-9]*)"."([0-9]+)

add "+"

sub "-"

mul "*"

div "/"

pow "^"

ln \n

%%

{dig} {digi();}

{add} {op=1;}

{sub} {op=2;}

{mul} {op=3;}

{div} {op=4;}

{pow} {op=5;}

{ln} {printf("\n The Answer :%f\n\n",a);}

%%

void digi()
{

if(op == 0)

/* atof() is used to convert the ASCII input to float */

a=atof(yytext);

else

b=atof(yytext);

switch(op)

case 1:a=a+b;

break;

case 2:a=a-b;

break;

case 3:a=a*b;

break;

case 4:a=a/b;

break;

case 5:

for(i=a;b>1;b--)

a=a*i;

}
break;

op=0;

int main(int argc,char *argv[])

yylex();

return 0;

int yywrap()

return 1;

Output:
30+21

The Answer :51.000000


WEEK 1:
%{

#include <stdio.h>

#include <unistd.h>

#include <string.h>

// Define a function to check if a word is a reserved keyword

int is_keyword(const char* word) {

const char* keywords[] = {

"auto", "break", "case", "char", "const", "continue", "default",

"do", "double", "else", "enum", "extern", "float", "for",

"goto", "if", "inline", "int", "long", "register", "restrict",

"return", "short", "signed", "sizeof", "static", "struct",

"switch", "typedef", "union", "unsigned", "void", "volatile",

"while", "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex",

"_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local"

};

int n_keywords = sizeof(keywords) / sizeof(char*);

for (int i = 0; i < n_keywords; ++i) {

if (strcmp(word, keywords[i]) == 0) {

return 1;

return 0;

%}
%%

[a-zA-Z_][a-zA-Z0-9_]* {

if (is_keyword(yytext)) {

printf("Found keyword: %s\n", yytext);

} else {

printf("Found identifier: %s\n", yytext);

[ \t\n]+ { /* Ignore whitespace */ }

. { /* Ignore any other character */ }

%%

int main() {

yylex();

return 0;

int yywrap() {

return 1;

input:
int main() {

int a = 10;

float b = 20.5;

if (a > b) {

return 1;

} else {
return 0;

Output:
int main() {

Found keyword: int

Found identifier: main

int a = 10;

Found keyword: int

Found identifier: a

float b = 20.5;

Found keyword: float

Found identifier: b

if (a > b) {

Found keyword: if

Found identifier: a

Found identifier: b

return 1;

Found keyword: return

} else {

Found keyword: else

return 0;

Found keyword: return

}
WEEK 2:
#include <stdio.h>

#include <string.h>

char prol[7][10] = { "S", "A", "A", "B", "B", "C", "C" };

char pror[7][10] = { "A", "Bb", "Cd", "aB", "@", "Cc", "@" };

char prod[7][10] = { "S->A", "A->Bb", "A->Cd", "B->aB", "B->@", "C->Cc", "C->@" };

char first[7][10] = { "abcd", "ab", "cd", "a@", "@", "c@", "@" };

char follow[7][10] = { "$", "$", "$", "a$", "b$", "c$", "d$" };

char table[5][6][10];

int numr(char c)

switch (c)

case 'S':

return 0;

case 'A':

return 1;

case 'B':

return 2;

case 'C':

return 3;

case 'a':

return 0;

case 'b':

return 1;
case 'c':

return 2;

case 'd':

return 3;

case '$':

return 4;

return (2);

int main(){

int i, j, k;

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

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

strcpy(table[i][j], " ");

printf("The following grammar is used for Parsing Table:\n");

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

printf("%s\n", prod[i]);

printf("\nPredictive parsing table:\n");

fflush(stdin);

for (i = 0; i < 7; i++) {

k = strlen(first[i]);

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

if (first[i][j] != '@')

strcpy(table[numr(prol[i][0]) + 1][numr(first[i][j]) + 1], prod[i]);

}
for (i = 0; i < 7; i++)

if (strlen(pror[i]) == 1)

if (pror[i][0] == '@')

k = strlen(follow[i]);

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

strcpy(table[numr(prol[i][0]) + 1][numr(follow[i][j]) + 1], prod[i]);

} strcpy(table[0][0], " ");

strcpy(table[0][1], "a");

strcpy(table[0][2], "b");

strcpy(table[0][3], "c");

strcpy(table[0][4], "d");

strcpy(table[0][5], "$");

strcpy(table[1][0], "S");

strcpy(table[2][0], "A");

strcpy(table[3][0], "B");

strcpy(table[4][0], "C");

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

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

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

{
printf("%-10s", table[i][j]);

if (j == 5)

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

}}

Output:
The following grammar is used for Parsing Table:

S->A

A->Bb

A->Cd

B->aB

B->@

C->Cc

C->@

Predictive parsing table:

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

a b c d $

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

S S->A S->A S->A S->A

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

A A->Bb A->Bb A->Cd A->Cd

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

B B->aB B->@ B->@ B->@

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

C C->@ C->@ C->@

--------------------------------------------------------
WEEK 3:
#include <stdio.h>

#include <string.h>

#include <ctype.h>

int temp_count = 0;

void generate_three_address_code(char* expression) {

int i = 0;

char temp[2];

char op;

char left_operand, right_operand;

while (expression[i] != '\0') {

if (isalnum(expression[i])) {

if (expression[i+1] == '+' || expression[i+1] == '-' || expression[i+1] == '*' ||

expression[i+1] == '/') {

left_operand = expression[i];

op = expression[++i];

right_operand = expression[++i];

// Generate temporary variable name

sprintf(temp, "t%d", temp_count++);

// Print the three-address code

printf("%s = %c %c %c\n", temp, left_operand, op, right_operand);

i++;
}

int main () {

char expression [100];

printf ("Enter an arithmetic expression: ");

gets(expression);

printf ("Three-address code:\n");

generate_three_address_code(expression);

return 0;

Input:
a+b*c

output:
Enter an arithmetic expression: a+b*c

Three-address code:

t0 = a +
WEEK 4:
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Define constants for actions

#define SHIFT 1

#define REDUCE 2

#define ACCEPT 3

#define ERROR 4

// Token definitions

#define TOK_IDENTIFIER 1

#define TOK_PLUS 2

#define TOK_STAR 3

#define TOK_LPAREN 4

#define TOK_RPAREN 5

#define TOK_END 6

// Define the Production structure

typedef struct {

int lhs;

int rhs_len;

} Production;

// Define the action structure

typedef struct {

int action;

int value;
} Action;

// Define the parsing table

Action ACTION[10][7];

int GOTO[10][5];

// Define the stack

typedef struct {

int state;

int symbol;

} StackItem;

StackItem stack[100];

int top = -1;

int input[] = {TOK_IDENTIFIER, TOK_PLUS, TOK_IDENTIFIER, TOK_END};

int input_pos = 0;

// Function to get the next token

int get_next_token() {

return input[input_pos++];

// Function to get production based on the production number

Production get_production(int p) {

Production productions[] = {

{0, 1}, // Example production

{1, 3},

// Add more productions as needed

};

return productions[p];
}

// Push item to stack

void push(int state, int symbol) {

stack[++top].state = state;

stack[top].symbol = symbol;

// Pop item from stack

StackItem pop() {

return stack[top--];

// Peek top of the stack

StackItem peek() {

return stack[top];

// Parsing function

void parse() {

int lookahead = get_next_token(); // Get next token

push(0, 0); // Push initial state

while (1) {

int state = peek().state;

Action action = ACTION[state][lookahead];

if (action.action == SHIFT) {

push(action.value, lookahead);

lookahead = get_next_token(); // Get next token

} else if (action.action == REDUCE) {


Production p = get_production(action.value);

for (int i = 0; i < p.rhs_len; ++i) {

pop();

int goto_state = GOTO[peek().state][p.lhs];

push(goto_state, p.lhs);

} else if (action.action == ACCEPT) {

printf("Input accepted\n");

return;

} else {

printf("Error in input\n");

return;

int main() {

// Initialize the parsing table with some dummy values for the example

ACTION[0][TOK_IDENTIFIER] = (Action){SHIFT, 1};

ACTION[1][TOK_PLUS] = (Action){SHIFT, 2};

ACTION[2][TOK_IDENTIFIER] = (Action){SHIFT, 3};

ACTION[3][TOK_END] = (Action){ACCEPT, 0};

GOTO[0][0] = 1; // Example GOTO table initialization

// Parse the input

parse();

return 0;
}

Output:

Input accepted
Week 5:
<program> ::= <block>

<block> ::= { <variabledefinition> <slist> }

| { <slist> }

<variabledefinition> ::= int <vardeflist> ;

<vardeflist> ::= <vardec> | <vardec> , <vardeflist>

<vardec> ::= <identifier> | <identifier> [ <constant> ]

<slist> ::= <statement> | <statement> ; <slist>

<statement> ::= <assignment>

| <ifstatement>

| <whilestatement>

| <block>

| <printstatement>

| <empty>

<assignment> ::= <identifier> = <expression>

| <identifier> [ <expression> ] = <expression>

<ifstatement> ::= if <bexpression> then <slist> else <slist> endif

| if <bexpression> then <slist> endif

<whilestatement> ::= while <bexpression> do <slist> enddo

<printstatement> ::= print ( <expression> )

<expression> ::= <expression> <addingop> <term>

| <term>

<addingop> ::= + | -

<term> ::= <term> <multop> <factor>

| <factor>
<multop> ::= * | /

<factor> ::= <constant>

| <identifier>

| <identifier> [ <expression> ]

| ( <expression> )

<constant> ::= <digit>

| <digit> <constant>

<identifier> ::= <identifier> <letterordigit>

| <letter>

<letterordigit> ::= <letter>

| <digit>

<letter> ::= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z

<digit> ::= 0|1|2|3|4|5|6|7|8|9

<empty> ::= ε
Program :
#include <stdio.h>

#include <stdlib.h>

// Constants for tokens

enum {

TOK_INT, TOK_IF, TOK_THEN, TOK_ELSE, TOK_ENDIF, TOK_WHILE,

TOK_DO, TOK_ENDDO, TOK_PRINT, TOK_PLUS, TOK_MINUS, TOK_MULTIPLY,

TOK_DIVIDE, TOK_EQUAL, TOK_SEMICOLON, TOK_LBRACE, TOK_RBRACE,

TOK_LPAREN, TOK_RPAREN, TOK_LBRACKET, TOK_RBRACKET, TOK_ID,

TOK_CONSTANT, TOK_EPSILON, TOK_EOF, TOK_GREATER_THAN

};

// Constants for actions

enum {

SHIFT, REDUCE, ACCEPT

};

// Data structures

typedef struct {

int type;

char value[50]; // Adjust as necessary for identifier and constant values

} Token;

typedef struct {

int action;

int state;

int production_len; // Length of RHS for reduction

} Action;
typedef struct {

int state;

int symbol;

} Goto;

// Action and Goto tables (dummy initialization for example)

Action action_table[10][24] = {

// Example table (dummy initialization)

{ {SHIFT, 1, 0}, {REDUCE, 0, 3}, {SHIFT, 2, 0}, {SHIFT, 3, 0}, {REDUCE, 1, 3},

{REDUCE, 2, 3}, {SHIFT, 4, 0}, {REDUCE, 3, 3}, {REDUCE, 4, 3}, {REDUCE, 5, 3},

{REDUCE, 6, 3}, {REDUCE, 7, 3}, {SHIFT, 5, 0}, {SHIFT, 6, 0}, {SHIFT, 7, 0},

{SHIFT, 8, 0}, {SHIFT, 9, 0}, {SHIFT, 10, 0}, {SHIFT, 11, 0}, {SHIFT, 12, 0},

{SHIFT, 13, 0}, {SHIFT, 14, 0}, {SHIFT, 15, 0}, {SHIFT, 16, 0}

},

// Add more states as per your grammar

};

Goto goto_table[10][9] = {

// Example table (dummy initialization)

{ {1, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0} },

// Add more entries as per your grammar

};

// Stack operations (simplified)

typedef struct {

int items[100];

int top;

} Stack;
void push(Stack *stack, int item) {

stack->items[++stack->top] = item;

int pop(Stack *stack) {

return stack->items[stack->top--];

int top(Stack *stack) {

return stack->items[stack->top];

// Parsing function

void parse(int tokens[], int num_tokens) {

Stack stack;

stack.top = -1;

push(&stack, 0); // Push initial state

int lookahead = tokens[0];

int idx = 1;

while (1) {

int state = top(&stack);

Action action = action_table[state][lookahead];

if (action.action == SHIFT) {

push(&stack, lookahead);

push(&stack, action.state);

lookahead = tokens[idx++];

} else if (action.action == REDUCE) {

// Perform reduction
int reduce_length = action.production_len;

int lhs = action.state; // Adjust based on the grammar and production rules

// Pop symbols from stack based on reduce_length

for (int i = 0; i < reduce_length; ++i) {

pop(&stack);

int goto_state = goto_table[top(&stack)][lhs].state;

push(&stack, lhs);

push(&stack, goto_state);

} else if (action.action == ACCEPT) {

printf("Parsing successful!\n");

break;

} else {

printf("Syntax error!\n");

break;

int main() {

int tokens[] = {TOK_LBRACE, TOK_INT, TOK_ID, TOK_LBRACKET, TOK_CONSTANT,

TOK_RBRACKET,

TOK_SEMICOLON, TOK_ID, TOK_EQUAL, TOK_CONSTANT, TOK_SEMICOLON,

TOK_ID, TOK_LBRACKET, TOK_CONSTANT, TOK_RBRACKET, TOK_EQUAL,

TOK_CONSTANT, TOK_SEMICOLON, TOK_IF, TOK_ID, TOK_GREATER_THAN,

TOK_CONSTANT, TOK_THEN, TOK_PRINT, TOK_LPAREN, TOK_ID, TOK_RPAREN,


TOK_SEMICOLON, TOK_ELSE, TOK_LBRACE, TOK_INT, TOK_ID, TOK_SEMICOLON,

TOK_ID, TOK_EQUAL, TOK_MINUS, TOK_CONSTANT, TOK_SEMICOLON,

TOK_PRINT,

TOK_LPAREN, TOK_MINUS, TOK_ID, TOK_PLUS, TOK_CONSTANT,

TOK_MULTIPLY,

TOK_ID, TOK_RPAREN, TOK_SEMICOLON, TOK_RBRACE, TOK_ENDIF,

TOK_RBRACE,

TOK_EOF};

int num_tokens = sizeof(tokens) / sizeof(tokens[0]);

parse(tokens, num_tokens);

return 0;

Output:

You might also like