Check the Resources link for samples. You can take them as a starting point.
Recognize | Action |
---|---|
Arithmetic (+, -, *, /) | Print the operator along with the line number |
Relational (<, <=, >, >=, !=, ==) | Print the operator along with the line number |
Assignment (=) | Print the operator along with the line number |
Parenthesis (left and right ones) | No action for now |
Some set of Reserved Words (for, if, while, int, ...) | Print the Reserved word along with the line number |
Identifiers | Insert into a table and keep track of the line number |
Numbers | Print the number (should handle integer and floating point) along with the line number |
At the end, print the number of distinct identifiers and the line numbers on which they occur.
Sample Input:
int i, n, sum; i = 1; n = 10; sum = 0; while (i <= n) { sum = sum + i; i = i + 1; }
Corresponding Sample Output:
Found keyword int on line 1 Found Assignment on line 2 Found number 1 on line 2 Found Assignment on line 3 Found number 10 on line 3 Found Assignment on line 4 Found number 0 on line 4 Found keyword while on line 5 Found operator <= on line 5 Found Assignment on line 7 Found operator + on line 7 Found Assignment on line 8 Found operator + on line 8 Found number 1 on line 8 The following are the identifers: Identifier i occurs on lines: 1, 2, 5, 7, 8 (2 times) Identifier n occurs on lines: 1, 3, 5 Identifier sum occurs on lines: 1, 4, 7 (2 times)
Running the Lex program
1. Write the Lex specifications as described above in a file, say, hw1.l 2. On Unix systems, do the following: % lex hw1.l (Produces lex.yy.c as the output) % cc lex.yy.c -ll (Compile the C file and link with Lex library) % a.out (Run the executable, and type the input, followed by) or, if the input is in a file, say, hw1.in, then do the following: % a.out < hw1.in