0% found this document useful (0 votes)
16 views13 pages

cd lab alg output

The document outlines various algorithms for implementing different types of lexical analyzers and parsers in C, including a lexical analyzer using C, Lex, and Yacc, as well as algorithms for counting lines, words, and characters. It also covers the conversion of epsilon NFA to NFA, NFA to DFA, and the minimization of DFA, along with the implementation of first and follow sets in grammar. Additionally, it describes a recursive descent parser for arithmetic expressions.
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)
16 views13 pages

cd lab alg output

The document outlines various algorithms for implementing different types of lexical analyzers and parsers in C, including a lexical analyzer using C, Lex, and Yacc, as well as algorithms for counting lines, words, and characters. It also covers the conversion of epsilon NFA to NFA, NFA to DFA, and the minimization of DFA, along with the implementation of first and follow sets in grammar. Additionally, it describes a recursive descent parser for arithmetic expressions.
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/ 13

LEXICAL ANALYSER USING C

ALGORITHM:
1. start the program
2. Open the file "input.txt" for reading.
3. If the file fails to open, display an error message and exit the program.
4. Read the file character by character until the end of file is reached.
5. If the character is an operator and not a keyword, print "id".
6. Check if the character is any of the operators. If so, print the corresponding operator token.
7. If the character is alphanumeric, store it in the buffer array.
8. If the character is a space or newline and the buffer is not empty, check if the buffer contains
a keyword. If so, print "kwd".
9. Close the file.
10. Return 0 to indicate successful execution of the program.
11. Stop the program

NOTE: The kwd() function is used to check if a given string (buffer) is a keyword. It compares the
string with an array of keywords and returns a flag indicating whether it is a keyword or not.

LEXICAL ANALYSER USING LEX TOOL


The given code is a Lex program that acts as a lexical analyzer for the C programming language. It
recognizes different components of C code such as keywords, identifiers, operators, numbers, strings,
etc. It tokenizes the input source code and prints the corresponding token for each recognized
component.

Algorithm:

1. start the program


2. 2.The program starts by defining the necessary regular expressions and lexer states using the
`%{ ... %}` block.
3. The `identifier` pattern is defined as a regular expression for matching valid C identifiers.
4. The `%%` block is used to define the lexer rules and corresponding actions.
5. Each rule consists of a pattern and an associated action to be executed when the pattern is
matched.
6. The lexer rules cover various C constructs such as keywords, operators, function calls, block
beginnings and endings, strings, and numbers.
7. The actions are responsible for printing the corresponding token or performing specific
operations based on the matched pattern.
8. The `yywrap()` function is called when the end of the input file is reached.
9. In the main function, the input file "input.c" is opened and assigned to `yyin`.
10. The `yylex()` function starts the lexical analysis process.
11. The resulting tokens are printed, and the program terminates.
12. Stop the program

DISPLAY NUMBER OF LINES WORDS & CHARACTERS IN INPUT TEXT


ALGORITHM:
1. 1.start the program
2. Declare and initialize variables sc (space count), wc (word count), lc (line count), and cc
(character count) to 0.

3. In the lexer rules section, define the following rules:


- Whenever a newline character is encountered, increment lc (line count) and cc
(character count) by the length of the newline.
- Whenever a space or tab character is encountered, increment sc (space count) and cc
(character count) by the length of the space or tab.
- Whenever a sequence of non-space, non-tab, non-newline characters is encountered,
increment wc (word count) and cc (character count) by the length of the sequence.

4. In the main function, check if the program was executed with a command-line argument (argc
== 2). If true, open the file specified by argv[1] for reading using fopen and assign it to yyin
(input stream). If false, prompt the user to enter input and assign stdin (standard input) to
yyin.

5. Call yylex() to start the lexical analysis process.

6. Print the values of lc (line count), sc (space count), wc (word count), and cc (character count)
using printf statements.

7. Implement the yywrap() function, which is called when the end of the input is reached. In this
case, return 1 to signal the end of the analysis process.
8. Stop the program
VOWELS AND CONSONANTS
Algorithm:
1. Start the program
2. Initialize variables v and c to 0.
3. Define the lexer rules using the regular expressions and corresponding actions.
- For every vowel (lowercase or uppercase), increment v by 1.
- For every alphabet (lowercase or uppercase), increment c by 1.
- When a newline character is encountered, print the number of vowels and reset v to
0. If there are no vowels, nothing will be printed.
- When a newline character is encountered, print the number of consonants and reset
c to 0. If there are no consonants, nothing will be printed.
4. Define the main function.
- Prompt the user to enter a string of vowels and consonants.
- Call yylex to start processing the input.
- Return 0 to indicate successful execution.
5. Define the yywrap function.
- Return 1 to indicate the end of input.
6. Stop the program

NOTE: The algorithm essentially scans the input string character by character and counts the
number of vowels and consonants encountered. Once a newline character is encountered, it prints
the counts and resets the respective variables.

CALCULATOR USING LEX & YACC


Algorithm:
1. 1.start the program
2. Begin by including necessary header files and declaring external variables.
3. Define the lexer rules using regular expressions to match different patterns.
4. Define the lexer action for each token, such as converting a number string to an integer and
returning the token type.
5. Implement the yywrap() function to indicate the end of input.
6. Begin the YACC section by including necessary header files and declaring any required
variables.
7. Define the token types using the %token directive.
8. Define the precedence and associativity rules using the %left directive.
9. Define the grammar rules for the arithmetic expressions using production rules.
10. Implement the action for the top-level rule (ArithmeticExpression), which prints the result of
the expression and returns 0.
11. Implement the actions for each production rule, performing the arithmetic operation and
updating the value of $$ (the result) accordingly.
12. Handle the parentheses case separately, returning the value inside the parentheses.
13. Handle the case of a single number separately, returning the number itself.
14. Implement the main() function, which prompts the user for an arithmetic expression and
calls yyparse() to parse and evaluate it.
15. Print the result of the expression, unless an error occurred during parsing.
16. Implement the yyerror() function to handle syntax errors encountered during parsing, and
set the flag variable to indicate an error occurred.
17. Stop the program

EPSILON CLOSURE OF NFA


ALGORITHM:
1. 1.start the program
2. Define and initialize necessary arrays and variables .
3. 2. Ask the user to enter the number of states and store the value in n
4. 3. Ask the user to enter the number of transitions and store the value in t
5. 4. Ask the user to enter the transitions
6. 5. For t states use scanf to get the values of s1, trans, and s2
a. 5.1 If trans is equal to e, set arr[s1][s2] to 1
7. Print a message "The epsilon closures are : "
8. For i in the range of 0 to n-1, print the current state
a. 7.1. For i in the range of 0 to n-1, set visited[i] to 0
b. 7.2. Set the visited array to 0
c. 7.3. Call the function closure(i)
9. Define Closure function.
a. 8.1. set the visited value of i to 1
b. 8.2. For all remaining states , check if E transition exist and is not visited.
10. 8.2.1. If yes , call closure of that state.
a. 8.2.2. Call closure of current state ( for missing states due to recursion )
11. Stop the program

OUTPUT:

❯ ./a.out

Enter the no of states: 4

Enter number of transitions:4

Enter transitions

0e1

0e2

1e3

2e0

The epsilon closures are :


State q0 : {q0,q1,q3,q2}

State q1 : {q1,q3}

State q2 : {q2,q0,q1,q3}

State q3 : {q3}

EPSILON NFA TO NFA


ALGORITHM:
1 START THE PROGRAM
1. Define global variables enfa to represent the transitions of an NFA (non-deterministic
finite automaton), final to store the final states, and ntrans to store the number of
transitions.
2. Implement a function isin() that checks whether a character c is present in a given
string str. The function iterates over each character in str and returns 1 if c is found, 0
otherwise.
3. Define a function findFinalStates() that finds the final states of the NFA. Within the
function:
1. Initialize an empty string final.
2. Iterate over each transition in enfa.
3. If the target state of the transition is present in the string final and the input
symbol is 'e' (representing an epsilon transition), add the source state to the
string final.
4. Print the final states enclosed within curly braces using printf.
4. Stop the program

4444bhhu444ewh
444
OUTPUT:

Enter number of transitions:7


Enter transitions as
state symbol state
011
110
0e2
203
302
214
402
Final states:2
NFA transitions
011
110
003
014
203
302
214
402
Final states : {20}

NFA TO DFA
ALGORITHM

1. Start the program


2. Insert transitions, final states ,start states and symbols
3. inititialize states array with start state
4. initialize nfa states counter to 1 and nfa state pointer to 0
5. while state counter not equal to states pointer
i. initialize s to empty
ii. for each symbol
a. for each character in current state
a. for each transition
a. if transition is from current state character with
current symbol
a. append the next state of transition to s
b. if s is empty print state[state pointer] symbol dead state
c. else print state[state pointer] symbol s
a. if s is not in states array add it
b. Increment state counter
iii. Increment state pointer 6.for each state in state array
iv. if state contain any final state print the state
6. Stop the program

OUTPUT

Number of transitions and final state:


41
Start state:
a
Final states:
c
Symbols:
12
Transitions:
a1a
a2a
a2b
b2c

a1a
a 2 ab
ab 1 a
ab 2 abc
abc 1 a
abc 2 abc
Final states:{abc,}

MINIMISATION OF DFA
The given code is a program that minimizes a DFA (Deterministic Finite Automaton) using the
minimization algorithm. It takes as input the DFA table, the number of DFA states, the number of
symbols, and the final states of the DFA.

Here is the algorithm used in the code to minimize the DFA:


ALGORITHM:
1. Start the program
a. Initialize some variables and arrays to store the DFA information, including the
DFA table, final states, state names, and the optimized DFA table.
b. Read the DFA table and other information from input.
c. Print the original DFA table.
2. Initialize the equivalence classes for the DFA states using the final states.
3. Iterate until no further changes are made:
i. Create a new DFA table by merging the states in each equivalence class.
ii. If the new DFA table differs from the previous table, update the
equivalence classes.
iii. Otherwise, stop the iteration.
4. Get the new final states by checking if each equivalence class is a subset of the original
final states.
5. Print the minimized DFA table.
6. Stop the program

The output of the program will be the minimized DFA table after the optimization process.

Note : that the code is incomplete and requires additional implementation details, such as the
functions for loading the DFA table and other utility functions. Without those missing parts, we
cannot determine the complete behavior and correctness of the code.

OUTPUT

Number of states:3
Number of symbols:2
Enter transitions
Transition of A with input 0: B
Transition of A with input 1: A
Transition of B with input 0: C
Transition of B with input 1: B
Transition of C with input 0: B
Transition of C with input 1: C
Final states withut any seperation in cap letters:B C
DFA: STATE TRANSITION TABLE
| 0 1
-----+------------
A | B A
B | C B
C | B C
Final states = B
After minimizationDFA: STATE TRANSITION TABLE
| 0 1
-----+------------
A | B A
B | A B
Final states = B

FIRST AND FOLLOW


ALGORITHM

1. Start the program


2. Get the number of productions in the grammar.
3. Read the productions and store them in an array.
4. Get the element whose First and Follow need to be found.
5. Call the "first" function passing the element as argument.
a. If its a terminal, add itself to the first array.
b. Check if the Production rule start with passed element. If yes
i. check if the first element after '=' is an uppercase(Non-terminal)
or lowercase (terminal).
ii. If lower, add that to the first array.
iii. If upper, call first() on that element.
6. Call the "follow" function passing the element as argument.
a. if its Starting production, add $ to follow array.
b. For each production, check if the symbol appears in the production. If
yes:
i. If its not the last symbol in production, calculate the First of the
symbol
ii. if it's the last, calculate the Follow of the first symbol of that
production.
7. Print the First and Follow of the element.
8. Stop the program
Output

❯ ./a.out

No of prooductions : 3

Enter the productions :


S=aAbc
A=c
A=d

Element whose first & follow is to be found : S


First(S)={a }
Follow(S)={$ }

Continue(0/1) : 1

Element whose first & follow is to be found : A


First(A)={c d }
Follow(A)={b }

Continue(0/1) : 0

RECURSIVE DESCENT PARSER


ALGORITHM:
1. 1.Start the program
2. Start with the main function (main).
3. Initialize variables i and error.
4. Prompt the user to enter an arithmetic expression and store it in the 'input' array.
5. Call the E() function to start parsing the expression.
6. Check if the entire input string has been processed (strlen(input) == i) and no errors
have occurred (error == 0).
i. If true, print "String accepted..!!!"
ii. If false, print "String rejected..!!!"
7. End of the program.
8. Define the E() function:
i. Call the T() function, Eprime() function
.
9. Define the Eprime() function:
i. Check if the current character is '+' or '-'.
ii. If true:
- Increment i.
- Call the T() function.
- Call the Eprime() function.

10. Define the T() function:


1. Call the F() function.
ii. Call the Tprime() function.

11. Define the Tprime() function:


1. Check if the current character is '*' or '/'.
ii. If true:
- Increment i.
- Call the F() function.
- Call the Tprime() function.

12. Define the F() function:


a. Check if the current character is alphanumeric.
ii. If true, increment i.
iii. If false, check if the current character is '('.
- If true:
- Increment i.
- Call the E() function.
- Check if the current character is ')'.
- If true, increment i.
- If false, set error = 1.
- If false, set error = 1.
13. Stop the program

Note: The 'ep' in the grammar rules represents an empty or epsilon production, meaning that
the given non-terminal can be skipped or replaced with an empty string.

OUTPUT

❯ gcc recdescent.c
❯ ./a.out

Enter an arithmetic expression : a+b*c-(d/e)

String accepted..!!!

❯ ./a.out

Enter an arithmetic expression : a+b*

String rejected..!!!

SHIFT REDUCE PARSER


ALGORITHM:

1. Start the program


2. Initialize variables:
a. buffer: to store the input string
b. stk: to store the intermediate results
c. len: to store the length of the input string
3. Input the string to be parsed and store it in the buffer
4. Set the length of the input string to the variable "len"
5. For each character in the buffer, check if it and the next character form "id".
6. If the next 2 characters are "id", shift and store both characters into the stack.
7. If the characters are not "id", shift the character into the stack.
8. Call the check function to reduce the stack according to the grammar.
9. In the check function, check for the patterns 'id', 'E + E', 'E * E', and '(E)'.
10. If any of the patterns is found, replace it with 'E' in the stack and update the
stack.
11. Repeat steps 7-9 until the stack contains only one element and input becomes
empty
12. Stop the program
OUTPUT
❯ ./a.out

GRAMMAR is
E->E+E
E->E*E
E->(E)
E->id

Enter input string : id+id*id+id

stack input action

$id +id*id+id$ SHIFT->id


$E +id*id+id$ REDUCE TO E
$E+ id*id+id$ SHIFT->symbol +
$E+id *id+id$ SHIFT->id
$E+E *id+id$ REDUCE TO E
$E *id+id$ REDUCE TO E
$E* id+id$ SHIFT->symbol *
$E*id +id$ SHIFT->id
$E*E +id$ REDUCE TO E
$E +id$ REDUCE TO E
$E+ id$ SHIFT->symbol +
$E+id $ SHIFT->id
$E+E $ REDUCE TO E
$E $ REDUCE TO E

INTERMEDIATE CODE GENERATION


Write algorithm and output written in the rough record

You might also like