Program:
/*to divide the given program into lexemes*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct lex
{
char le[50],tok[20];
}l[50];
int t=0;
void main()
{
char data[200],ch;
int i,j=0,k=0,n;
clrscr();
printf("Enter the input:\n");
for(i=0;(ch=getchar())!=-1;i++ )
data[i]=ch;
data[i]='\0';
for(i=0;data[i]!='\0';i++)
{
if(spe(data[i]))
{
if(data[i-1]!='\n')
{
l[j++].le[k]='\0';
k=0;
}
l[j].le[k++]=data[i];
if(rel(data[i])&&rel(data[i+1] ))
{
l[j].le[k++]=data[i+1];
i=i+1;
}
}
else
{
if(data[i]==' '||data[i]=='\n')
{
l[j++].le[k]='\0';
k=0;
}
else
{
if(spe(data[i-1]))
{
l[j++].le[k]='\0';
k=0;
}
l[j].le[k++]=data[i];
}
}
}
n=j;
t=0;
for(i=0;i<=n;i++)
{
token(l[i].le);
t++;
}
printf("Lexeme\t\tToken\n");
printf("---------------------\ n");
for(i=0;i<=n;i++)
{
printf("%4s\t\t%4s\n",l[i].le, l[i].tok);
}
getch();
}
int spe(char c)
{
int i,c1=0,t,n;
char de[15]={'(',')','{','}','[','] ',';',',','/','*','+','-','=', '<','>'};
for(i=0;i<15;i++)
{
if(c==de[i])
{
c1=1;
break;
}
}
return c1;
}
int rel(char c)
{
int i,c1=0;
char rel1[8]={'<','>','=','!','+',' -','&','/'};
for(i=0;i<8;i++)
{
if(c==rel1[i])
{
c1=1;
break;
}
}
return c1;
}
token(char c[20])
{
char key[32][10]={"auto","break"," case","char","continue"," default",
"do","double","void","else"," enum","extern",
"float","goto","if","int"," long","register","return",
"short","signed","sizeof"," static","struct","switch",
"typedef","unsigned","union"," volatile","while"};
char oper[6][2]={"=","+","-","*","/ ","%"};
char relop[8][3]={"++","--","&&","| |","<=",">=","==","!="};
char par[2][2]={"(",")"};
char brac[2][2]={"{","}"};
char spe[7][2]={" ",",",";",":","?","[","]"};
int i,flag=0;
for(i=0;i<30;i++)
{
if(strcmp(c,key[i])==0)
{
strcpy(l[t].tok,"Keyword");
flag=1;
return;
}
}
for(i=0;i<6;i++)
{
if(strcmp(c,oper[i])==0)
{
strcpy(l[t].tok,"Arithmetic Operator");
flag=1;
return;
}
}
for(i=0;i<8;i++)
{
if(strcmp(c,relop[i])==0)
{
strcpy(l[t].tok,"Relational Operator");
flag=1;
return;
}
}
for(i=0;i<2;i++)
{
if(strcmp(c,par[i])==0)
{
strcpy(l[t].tok,"paranthesis") ;
flag=1;
return;
}
}
for(i=0;i<2;i++)
{
if(strcmp(c,brac[i])==0)
{
strcpy(l[t].tok,"Braces");
flag=1;
return;
}
}
for(i=0;i<7;i++)
{
if(strcmp(c,spe[i])==0)
{
strcpy(l[t].tok,"Special Symbol");
flag=1;
return;
}
}
if((strcmp(l[t].tok,"Keyword") !=0)&&(strcmp(l[t++].le,c)==0) )
{
strcpy(l[t].tok,"Function");
flag=1;
return;
}
if(flag==0)
{
strcpy(l[t].tok,"Identifier");
return;
}
return;
}
Output:
No comments:
Post a Comment