Program to implement the design of a Lexical analyzer to recognize the tokens defined by the given grammar

PROCEDURE:
We make use of the following two functions in the process.
look up() – it takes string as argument and checks its presence in the symbol table. If the
string is found then returns the address else it returns NULL.
insert() – it takes string as its argument and the same is inserted into the symbol table and
the corresponding address is returned.
1. Start
2. Declare an array of characters, an input file to store the input;
3. Read the character from the input file and put it into character type of variable, say ‘c’.
4. If ‘c’ is blank then do nothing.
5. If ‘c’ is new line character line=line+1.
6. If ‘c’ is digit, set token Val, the value assigned for a digit and return the ‘NUMBER’.
7. If ‘c’ is proper token then assign the token value.
8. Print the complete table with
Token entered by the user,
Associated token value.
9. Stop
[wp_ad_camp_1]
#include<string.h> #include<ctype.h> #include<stdio.h>void keyword(char str[10]) { if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("static",str)==0||strcmp("switch",str)==0||strcmp("case",str)==0) printf("\n%s is a keyword",str); else printf("\n%s is an identifier",str); } main() { FILE *f1,*f2,*f3; char c, str[10], st1[10]; int num[100], lineno=0, tokenvalue=0,i=0,j=0,k=0; printf("\n Enter the c program : ");/*gets(st1);*/ f1=fopen("input","w"); while((c=getchar())!=EOF) putc(c,f1); fclose(f1); f1=fopen("input","r"); f2=fopen("identifier","w"); f3=fopen("specialchar","w"); while((c=getc(f1))!=EOF) { if(isdigit(c)) { tokenvalue=c-'0'; c=getc(f1); while(isdigit(c)) { tokenvalue*=10+c-'0'; c=getc(f1); } num[i++]=tokenvalue; ungetc(c,f1); } else if(isalpha(c)) { putc(c,f2); c=getc(f1); while(isdigit(c)||isalpha(c)||c=='_'||c=='$') { putc(c,f2); c=getc(f1); } putc(' ',f2); ungetc(c,f1); } else if(c==' '||c=='\t') printf(" "); else if(c=='\n') lineno++; else putc(c,f3); } fclose(f2); fclose(f3); fclose(f1); printf("\n The no's in the program are :"); for(j=0; j<i; j++) printf("%d", num[j]); printf("\n"); f2=fopen("identifier", "r"); k=0; printf("The keywords and identifiers are:"); while((c=getc(f2))!=EOF) { if(c!=' ') str[k++]=c; else { str[k]='\0'; keyword(str); k=0; } } fclose(f2); f3=fopen("specialchar","r"); printf("\n Special characters are : "); while((c=getc(f3))!=EOF) printf("%c",c); printf("\n"); fclose(f3); printf("Total no. of lines are:%d", lineno); }[wp_ad_camp_1]
Output : Enter the C program: a+b*c Ctrl-D The no’s in the program are: The keywords and identifiers are: a is an identifier and terminal b is an identifier and terminal c is an identifier and terminal Special characters are: + * Total no. of lines are: 1