/* Lex code to count and list total number of tokens */
%{
#include <stdio.h>
#include <stdlib.h>
int n = 0; // Counter for total tokens
char* tokens[1000]; // Array to store tokens (up to 1000 tokens)
int tokenIndex = 0; // Index to store tokens
%}
/* Rule Section */
%%
"while"|"if"|"else" {
n++;
printf("\tkeyword: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
"int"|"float" {
n++;
printf("\tkeyword: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
[a-zA-Z_][a-zA-Z0-9_]* {
n++;
printf("\tidentifier: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
"<="|"=="|"="|"++"|"-"|"*"|"+" {
n++;
printf("\toperator: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
[(){}|,;] {
n++;
printf("\tseparator: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
[0-9]*"."[0-9]+ {
n++;
printf("\tfloat: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
[0-9]+ {
n++;
printf("\tinteger: %s\n", yytext);
tokens[tokenIndex++] = yytext; // Store the token
}
. ; // Ignore unrecognized characters
%%
/* Main function */
int main() {
yylex(); // Start lexical analysis
printf
("\nTotal
number of tokens
= %d\n", n); // Print total token count
// Print the list of tokens
printf("\nList of tokens:\n");
for (int i = 0; i < tokenIndex; i++) {
printf("%s\n", tokens[i]); // Print each token
}
return 0;
}
LyogTGV4IGNvZGUgdG8gY291bnQgYW5kIGxpc3QgdG90YWwgbnVtYmVyIG9mIHRva2VucyAqLwoKJXsKI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCmludCBuID0gMDsgICAgLy8gQ291bnRlciBmb3IgdG90YWwgdG9rZW5zCmNoYXIqIHRva2Vuc1sxMDAwXTsgICAvLyBBcnJheSB0byBzdG9yZSB0b2tlbnMgKHVwIHRvIDEwMDAgdG9rZW5zKQppbnQgdG9rZW5JbmRleCA9IDA7ICAgIC8vIElu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