Program 3: Implementation of Lexical Analyzer
using Lex Tool
Aim:
To write a Lex program that implements a lexical analyzer to:
1. Recognize a valid arithmetic expression using operators +, -, *, /.
2. Recognize valid variables that start with a letter and are followed by letters or digits.
<b>Algorithm:</b>
1. Start the program.
2. Include the required header files in the definition section.
3. Define regular expressions for:
- Numbers (integer and decimal).
- Operators.
- Identifiers (variable names).
4. In the rules section, associate each pattern with an action that prints the token type.
5. Ignore whitespace characters.
6. For any other character, print it as invalid.
7. Compile the lex file using the lex command.
8. Link and create the executable using gcc.
9. Run the program and test with different inputs.
10. Stop.
Source Code (program3.l):
%{
#include <stdio.h>
%}
%%
[0-9]+(\.[0-9]+)? { printf("Number: %s\n", yytext); }
[+\-*/] { printf("Operator: %s\n", yytext); }
[a-zA-Z][a-zA-Z0-9]* { printf("Identifier: %s\n", yytext); }
[ \t\n]+ { /* Ignore whitespace */ }
. { printf("Invalid character: %s\n", yytext); }
%%
int main() {
printf("Enter the expression or variable names:\n");
yylex();
return 0;
}
int yywrap() {
return 1;
}
Compilation and Execution Steps: 1. Save the program as program3.l 2. Open terminal and
compile: lex program3.l gcc [Link].c -o program3 -ll ./program3 3. Enter input when prompted.
<b>Sample Input:</b>
a1 + b2 * 45
sum1/total2
<b>Sample Output:</b>
Enter the expression or variable names:
Identifier: a1
Operator: +
Identifier: b2
Operator: *
Number: 45
Identifier: sum1
Operator: /
Identifier: total2
Result: The Lex program successfully recognizes numbers, arithmetic operators, and identifiers,
and ignores whitespace.