You are on page 1of 6

TOPIC: “LEXICAL ANALYZER “

SUBMITTED BY:
Laiba Sohail (4146-FBAS/BSCS/F19)

SUBMITTED TO:
DR NADEEM

DATE OF SUBMISSION:
19TH November, 2022

COMPILER CONSTRUCTION
ASSIGNMENT # 1

Department of Computer Science


Faculty of Computing
International Islamic University, H10, Islamabad
QUESTION:
Write a C++ code that implements the working of lexical
analyzer. Submit .cpp file and the picture of output screen.

#include<iostream>
#include<string>
using namespace std;
bool is_Letter(char ch);
bool is_Digit(char ch);
bool is_Delimeter(char ch);
void Lexical(string str);
int main()
{
string input;
cout << "Enter the string" << endl;
cout << "Token are " << endl;
getline(cin, input);
Lexical(input);
return 0;
}
bool is_Letter(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
return true;
else
return false;
}
bool is_Digit(char ch) {
if ((ch >= '0' && ch <= '9'))
return true;
else
return false;
}
bool is_Delimeter(char ch) {
if (ch == ' ' || ch == '\t' || ch == '\n')
return true;
else
return false;
}
void Lexical(string str)
{
int state = 0;
int i = 0;
string lexeme="";
int flag = 1;
char c = '\0';

while (str[i] != '\0')


{
c = str[i];
flag = 1;
switch (state)
{
case 0:
if (is_Letter(c))
{
state = 1;
}
else if (is_Digit(c))
{
state = 2;
}
else if (c == '=')
{
state = 0;
lexeme = c;
cout << "Token < " << "Assignment Operator , " << lexeme << " >
" << endl;
lexeme = "";
flag = 0;
}
else if (c == '+')
{
state = 0;
lexeme = c;
cout << "Token < " << "Addition Operator , " << lexeme << " > "
<< endl;
lexeme = "";
flag = 0;
}
else if (c == ';')
{
state = 0;
lexeme = c;
cout << "Token < " << "Semi Colon , " << lexeme << " > " <<
endl;
lexeme = "";
flag = 0;
}
else if (c == '<')
{
state = 3;

}
else if (c == '{')
{
state = 0;
lexeme = c;
cout << "Token < " << "Opening Parenthesis , " << lexeme << " >
" << endl;
lexeme = "";
flag = 0;
}
else if (c == '}')
{
state = 0;
lexeme = c;
cout << "Token < " << "Closing Parenthesis , " << lexeme << " > "
<< endl;
lexeme = "";
flag = 0;
}
else if (c == ',')
{
state = 0;
lexeme = c;
cout << "Token < " << "Comma , " << lexeme << " > " << endl;
lexeme = "";
flag = 0;
}
else if (is_Delimeter(c))
{
flag = 0;
}
else
{
cout << "Invalid Token" << endl;
break;
}
break;
case 1:
if (!(is_Letter(c) || is_Digit(c)))
{
state = 0;
if (lexeme == "int" || lexeme == "main" || lexeme == "cout")
{
cout << "Token < " << "Keyword, " << lexeme << " >" <<
endl;
}
else
{
cout << "Token < " << "Letter Occur, " << lexeme << " >"
<< endl;
}
lexeme = "";
continue;
}
break;
case 2:
if (!is_Digit(c))
{
state = 0;
cout << "Token < " << "Digit Occur, " << lexeme << " >" << endl;
lexeme = "";
continue;
}
break;

case 3:
if (c == '=')
{
state = 0;
cout << "Token < " << "LE, " << lexeme << " >" << endl;
lexeme = "";
continue;
}
else
{
state = 0;
cout << "Token < " << "LT, " << lexeme << " >" << endl;
lexeme = "";
continue;
}
break;

}
if(flag)
lexeme = lexeme + c;
i++;
}
}

You might also like