0% found this document useful (0 votes)
8 views34 pages

CD 1 to 11 Practical

The document contains code for token separation in programming expressions using C, including functions to identify delimiters, operators, keywords, integers, real numbers, and valid identifiers. It also includes a program that reads from a file and detects tokens, as well as a lexer implementation using LEX tools for lexical analysis. Additionally, it discusses using YACC for creating a calculator and a recursive descent parser.

Uploaded by

cyberphantomad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views34 pages

CD 1 to 11 Practical

The document contains code for token separation in programming expressions using C, including functions to identify delimiters, operators, keywords, integers, real numbers, and valid identifiers. It also includes a program that reads from a file and detects tokens, as well as a lexer implementation using LEX tools for lexical analysis. Additionally, it discusses using YACC for creating a calculator and a recursive descent parser.

Uploaded by

cyberphantomad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

PRACTICAL – 01

Write a Program for Token separation with a given expression.

Code:
#include <stdbool.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

bool isDelimiter(char ch)

if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' || ch ==

'/' || ch == ',' || ch == ';' || ch == '>' || ch == '<' ||

ch == '=' || ch == '(' || ch == ')' || ch == '[' || ch ==

']' || ch == '{' || ch == '}') return (true);

return (false);

bool isOperator(char ch)

if (ch == '+' || ch == '-' || ch == '*' || ch

== '/' || ch == '>' || ch == '<' || ch ==

'=')

return (true);

return (false);

bool validIdentifier(char* str)

if (str[0] == '0' || str[0] == '1' || str[0] == '2' ||

str[0] == '3' || str[0] == '4' || str[0] == '5' ||


str[0] == '6' || str[0] == '7' || str[0] == '8' || str[0]

== '9' || isDelimiter(str[0]) == true) return

(false);

return (true);

bool isKeyword(char* str)

if (!strcmp(str, "if") || !strcmp(str, "else") ||

!strcmp(str, "while") || !strcmp(str, "do") ||

!strcmp(str, "break") ||

!strcmp(str, "continue") || !strcmp(str, "int")

|| !strcmp(str, "double") || !strcmp(str, "float")

|| !strcmp(str, "return") || !strcmp(str, "char")

|| !strcmp(str, "case") || !strcmp(str, "char")

|| !strcmp(str, "sizeof") || !strcmp(str, "long")

|| !strcmp(str, "short") || !strcmp(str, "typedef")

|| !strcmp(str, "switch") || !strcmp(str, "unsigned")

|| !strcmp(str, "void") || !strcmp(str, "static")

|| !strcmp(str, "struct") || !strcmp(str, "goto")) return

(true);

return (false);

bool isInteger(char* str)

int i, len = strlen(str); if

(len == 0)

return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'

&& str[i] != '3' && str[i] != '4' && str[i] != '5'

&& str[i] != '6' && str[i] != '7' && str[i] != '8'

&& str[i] != '9' || (str[i] == '-' && i > 0))

return (false);

return (true);

bool isRealNumber(char* str)

int i, len = strlen(str); bool

hasDecimal = false; if (len ==

0)

return (false);

for (i = 0; i < len; i++) {

if (str[i] != '0' && str[i] != '1' && str[i] != '2'

&& str[i] != '3' && str[i] != '4' && str[i] != '5'

&& str[i] != '6' && str[i] != '7' && str[i] != '8'

&& str[i] != '9' && str[i] != '.' ||

(str[i] == '-' && i > 0)) return

(false);

if (str[i] == '.') hasDecimal

= true;

return (hasDecimal);

}
char* subString(char* str, int left, int right)

{
int i;

char* subStr = (char*)malloc( sizeof(char) *

(right - left + 2));

for (i = left; i <= right; i++)

subStr[i - left] = str[i];

subStr[right - left + 1] = '\0';

return (subStr);

void parse(char* str)

int left = 0, right = 0; int

len = strlen(str);

while (right <= len && left <= right) { if

(isDelimiter(str[right]) == false)

right++;

if (isDelimiter(str[right]) == true && left == right) { if

(isOperator(str[right]) == true)

printf("'%c' IS AN OPERATOR\n", str[right]);

right++;

left = right;

} else if (isDelimiter(str[right]) == true && left != right

|| (right == len && left != right)) { char*

subStr = subString(str, left, right - 1); if

(isKeyword(subStr) == true)
printf("'%s' IS A KEYWORD\n", subStr); else if

(isInteger(subStr) == true)

printf("'%s' IS AN INTEGER\n", subStr);


else if (isRealNumber(subStr) == true) printf("'%s' IS

A REAL NUMBER\n", subStr);

else if (validIdentifier(subStr) == true

&& isDelimiter(str[right - 1]) == false) printf("'%s' IS

A VALID IDENTIFIER\n", subStr);

else if (validIdentifier(subStr) == false

&& isDelimiter(str[right - 1]) == false)

printf("'%s' IS NOT A VALID IDENTIFIER\n", subStr); left

= right;

return;

int main()

char str[100] = "int a = b + 1c; ";

parse(str);

return (0);

Output :
PRACTICAL - 02

Write a Program for Token separation with a given file.


Code:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
bool isValidDelimiter(char ch) {
if (ch == ' ' || ch == '+' || ch == '-' || ch == '*' || ch
== '/' || ch == ',' || ch == ';' || ch == '>'
|| ch == '<' || ch == '=' || ch == '(' || ch == ')' || ch ==
'[' || ch == ']' || ch == '{' || ch == '}')
return (true);
return (false); }
bool isValidOperator(char ch) {
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch
== '>' || ch == '<' || ch == '=')
return (true);
return (false); }
bool isvalidIdentifier(char* str) {
if (str[0] == '0' || str[0] == '1' || str[0] == '2' || str[0]
== '3' || str[0] == '4' || str[0] == '5' ||
str[0] == '6' || str[0] == '7' || str[0] == '8' ||str[0] ==
'9' || isValidDelimiter(str[0]) ==
true)
return (false);
return (true); }
bool isValidKeyword(char* str) {
if (!strcmp(str, "if") || !strcmp(str, "else")
|| !strcmp(str, "while") || !strcmp(str, "do") ||
!strcmp(str, "break") || !strcmp(str, "continue")
|| !strcmp(str, "int") || !strcmp(str,
"double") || !strcmp(str, "float") || !strcmp(str,
"return") || !strcmp(str, "char") ||
!strcmp(str, "case") || !strcmp(str, "char")
|| !strcmp(str, "sizeof") || !strcmp(str, "long")
|| !strcmp(str, "short") || !strcmp(str, "typedef")
|| !strcmp(str, "switch") || !strcmp(str,
"unsigned") || !strcmp(str, "void") || !strcmp(str,
"static") || !strcmp(str, "struct") ||
!strcmp(str, "goto"))
return (true);
return (false); }
bool isValidInteger(char* str) {
int i, len = strlen(str);
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2'&&
str[i] != '3' && str[i] != '4'
&& str[i] !='5' && str[i] != '6' && str[i] != '7' &&
str[i] != '8' && str[i] != '9' ||
(str[i] == '-' && i > 0))
return (false); }
return (true); }
bool isRealNumber(char* str) {
int i, len = strlen(str);
bool hasDecimal = false;
if (len == 0)
return (false);
for (i = 0; i < len; i++) {
if (str[i] != '0' && str[i] != '1' && str[i] != '2' &&
str[i] != '3' && str[i] != '4'
&& str[i] != '5' && str[i] != '6' && str[i] != '7'
&& str[i] != '8' && str[i] != '9'
&& str[i] != '.' || (str[i] == '-' && i > 0))
return (false);
if (str[i] == '.')
hasDecimal = true; }
return (hasDecimal); }
char* subString(char* str, int left, int right) {
int i;
char* subStr = (char*)malloc( sizeof(char) * (right
- left + 2));
for (i = left; i <= right; i++)
subStr[i - left] = str[i];
subStr[right - left + 1] = '\0';
return (subStr); }
void detectTokens(char* str) {
int left = 0, right = 0;
int length = strlen(str);
while (right <= length && left <= right) {
if (isValidDelimiter(str[right]) == false)
right++;
if (isValidDelimiter(str[right]) == true && left
== right) {
if (isValidOperator(str[right]) == true)
printf("Valid operator : '%c'\n", str[right]);
right++;
left = right; }
else if (isValidDelimiter(str[right]) == true &&
left != right || (right == length
&& left!= right)) {
char* subStr = subString(str, left, right - 1);
if (isValidKeyword(subStr) == true)
printf("Valid keyword : '%s'\n", subStr);
else if (isValidInteger(subStr) == true)
printf("Valid Integer : '%s'\n", subStr);
else if (isRealNumber(subStr) == true)
printf("Real Number : '%s'\n", subStr);
else if(isvalidIdentifier(subStr) == true &&
isValidDelimiter(str[right -
1]) == false)
printf("Valid Identifier : '%s'\n", subStr);
else if (isvalidIdentifier(subStr) == false &&
isValidDelimiter(str[right - 1]) == false)
printf("Invalid Identifier : '%s'\n", subStr);
left = right; } }
return; }
int main() {
FILE *input_fp = fopen("program.c", "r");
if (input_fp == NULL) {
printf("Error: unable to open input file.\n");
return 1; }
fseek(input_fp, 0L, SEEK_END);
int input_file_size = ftell(input_fp);
fseek(input_fp, 0L, SEEK_SET);
char *input_buffer = malloc(input_file_size +
1);
if (input_buffer == NULL) {
printf("Error: unable to allocate input
buffer.\n");
fclose(input_fp);
return 1; }
int num_bytes_read = fread(input_buffer, 1,
input_file_size, input_fp);
input_buffer[num_bytes_read] = '\0';
fclose(input_fp);
printf("The Program is :\n%s\n", input_buffer);
printf("All Tokens are : \n");
detectTokens(input_buffer);
free(input_buffer);
return (0); } FILE *input_fp = fopen("program.c",
"r"); if (input_fp == NULL) {
printf("Error: unable to open input file.\n");
return 1; }
fseek(input_fp, 0L, SEEK_END);
int input_file_size = ftell(input_fp);
fseek(input_fp, 0L, SEEK_SET);

char *input_buffer = malloc(input_file_size + 1);


if (input_buffer == NULL) {
printf("Error: unable to allocate input buffer.\n");
fclose(input_fp);
return 1; }
int num_bytes_read = fread(input_buffer, 1, input_file_size, input_fp);
input_buffer[num_bytes_read] = '\0';
fclose(input_fp);
printf("The Program is :\n%s\n", input_buffer);
printf("All Tokens are : \n");
detectTokens(input_buffer);
free(input_buffer);
return (0); }

Output:
PRACTICAL - 03

Write a Program for Lexical analysis using LEX tools.


Code:
File: lexer.l
%{
#include <stdio.h>
%}
%%
"if" { printf("Keyword: if\n"); }
"else" { printf("Keyword: else\n"); }
"int" { printf("Keyword: int\n"); }
"char" { printf("Keyword: char\n"); }
"return" { printf("Keyword: return\n"); }
"+" { printf("Operator: +\n"); }
"-" { printf("Operator: -\n"); }
"*" { printf("Operator: *\n"); }
"/" { printf("Operator: /\n"); }
"==" { printf("Operator: ==\n"); }
"!=" { printf("Operator: !=\n"); }
">" { printf("Operator: >\n"); }
"<" { printf("Operator: <\n"); }
">=" { printf("Operator: >=\n"); }
"<=" { printf("Operator: <=\n"); }
"=" { printf("Assignment Operator: =\n"); }
"(" { printf("Left Parenthesis: (\n"); }
")" { printf("Right Parenthesis: )\n"); }
"{" { printf("Left Brace: {\n"); }
"}" { printf("Right Brace: }\n"); }
";" { printf("Semicolon: ;\n"); }
"," { printf("Comma: ,\n"); }
"\"" { printf("Double Quote: \"\n"); }
"'" { printf("Single Quote: '\n"); }
[0-9]+ { printf("Integer Literal: %s\n", yytext); }
[a-zA-Z_][a-zA-Z0-9_]* { printf("Identifier: %s\n", yytext); }
[ \t\n] ; // Ignore whitespace
. { printf("Invalid Token: %s\n", yytext); }
%%
int main()
{ yylex();
return 0; }

Output:

File: program.c
PRACTICAL - 09

Study of LEX and YACC tools.


i) Write a Program for implementation of calculator using
YACC tool.
ii) Write a Program for implementation of Recursive Descent Parser
using LEX tool.
Code: (i)
File: Parser.y -
%{
#include <stdio.h>
int yylex(void); // declare the lexer function
void yyerror(char *msg); // declare the error function
%}
%token NUM
%token + - * /
%%
expression:
expression '+' expression { printf("%d + %d\n", $1, $3); }
| expression '-' expression { printf("%d - %d\n", $1, $3); }
| expression '*' expression { printf("%d * %d\n", $1, $3); }
| expression '/' expression { printf("%d / %d\n", $1, $3); }
| NUM { $$ = $1; };
%%
int main(void) {
printf("Enter an arithmetic expression:\n");
yyparse(); // call the parser function
return 0; }
void yyerror(char *msg)
{ printf("%s\n", msg); }
File: lexer.l -
%{
#include <stdio.h>
#include "parser.tab.h"
%}
%%
[0-9]+ { yylval.num = atoi(yytext); return NUM; }
[+\-*/] { return yytext[0]; }
[ \t] ;
\n { return EOL; }
. { printf("Invalid character: %s\n", yytext); }
%%
File: Program.c -
#include <stdio.h>
#include "parser.tab.h"
extern FILE *yyin;
int main(int argc, char **argv)
{ if (argc < 2) {
printf("Usage: %s <input file>\n", argv[0]);
return 1; }
FILE *fp = fopen(argv[1], "r");
if (!fp) {
printf("Error: unable to open input file %s\n", argv[1]);
return 1; }
yyin = fp;
yyparse();
fclose(fp);
return 0;
}

Output :
(ii)
%{
#include <stdio.h>
%}
%%
[0-9]+ { printf("Saw an integer: %s\n", yytext); }
.{;}
%%
int main(){
printf("Enter some input that consists of an integer number\n");
yylex(); }
int
yywrap(){
return 1;
}

Output:
PRACTICAL - 10

Write a Program for implementation of LL(1) Parser.


Code:
#include<bits/stdc++.h>
using namespace std;
set<char> ss;
bool dfs(char i, char org, char last, map<char,vector<vector<char>>>
&mp){ bool rtake = false;
for(auto r :
mp[i]){ bool
take = true;
for(auto s : r){
if(s == i) break;
if(!take) break;
if(!(s>='A'&&s<='Z')&&s!='e'){ ss.inse
rt(s);
break; }
else if(s == 'e'){
if(org == i||i == last)
ss.insert(s);
rtake = true;
break; }
else{
take = dfs(s,org,r[r.size()-1],mp);
rtake |= take; }}}
return rtake; }
int main(){
int i,j;
ifstream fin("inputllcheck.txt");
string num;
vector<int> fs;
vector<vector<int>> a;
map<char,vector<vector<char>>> mp;
char start;

bool flag = 0;
cout<<"Grammar: "<<'\n';
while(getline(fin,num)){
if(flag == 0) start = num[0],flag = 1;
cout<<num<<'\n';
vector<char> temp;
char s = num[0];
for(i=3;i<num.size();i++){
if(num[i] ==
'|'){ mp[s].push_back(temp)
; temp.clear();}
else temp.push_back(num[i]); }
mp[s].push_back(temp); }
int flag2 = 0;
vector<char> del;
map<char,vector<vector<char>>> add;
vector<int> viz(100,0);
for(auto q :
mp){ int one
= 0; char c;
for(auto r :
q.second){ if(q.first
== r[0]){
one = 1;
flag2 = 1;
del.push_back(q.first);
c = 'A';
while(mp.count(c)||viz[c-'A']) c++;
vector<char> temp;
for(i=1;i<r.size();i++)
temp.push_back(r[i]);
temp.push_back(c);
add[c].push_back(temp);
add[c].push_back({'e'});}}
if(one){
for(auto r :
q.second){ if(q.first
!= r[0]){
vector<char> temp;
for(i=0;i<r.size();i++)
temp.push_back(r[i]);
temp.push_back(c);
add[q.first].push_back(temp); }}
viz[c-'A'] = 1; }}
for(auto q : del) mp.erase(q);
for(auto q : add) mp[q.first] = q.second;
if(flag2){
cout<<"\nGiven CFG is not suitable for LL1\nConverting...\n"<<'\n';
cout<<"New Grammar:"<<'\n';
for(auto q :
mp){ string
ans = "";
ans+=q.first;
ans += "->";
for(auto r :
q.second){ for(auto s : r)
ans+=s; ans+='|'; }
ans.pop_back();
cout<<ans<<'\n'; }}
else cout<<"\nGiven CFG is not suitable for LL1"<<'\n';
map<char,set<char>> fmp;
for(auto q :
mp){ ss.clear();
dfs(q.first,q.first,q.first,mp);
for(auto g : ss) fmp[q.first].insert(g); }
cout<<'\n';
cout<<"FIRST: "<<'\n';
for(auto q :
fmp){ string ans
= ""; ans +=
q.first; ans += "
= {";

for(char r :
q.second){ ans += r;
ans += ','; }
ans.pop_back();
ans+="}";
cout<<ans<<'\n'; }
map<char,set<char>> gmp;
gmp[start].insert('$');
int count = 10;
while(count--
){
for(auto q :
mp){ for(auto r :
q.second){
for(i=0;i<r.size()-1;i++){
if(r[i]>='A'&&r[i]<='Z'){
if(!(r[i+1]>='A'&&r[i+1]<='Z')) gmp[r[i]].insert(r[i+1]);
else {
char temp = r[i+1];
int j = i+1;
while(temp>='A'&&temp<='Z'){ if(*fmp[temp].begin()
=='e'){
for(auto g :
fmp[temp]){ if(g=='e')
continue;
gmp[r[i]].insert(g); }
j++;
if(j<r.size()){ t
emp = r[j];
if(!(temp>='A'&&temp<='Z')){
gmp[r[i]].insert(temp);
break; }}
else{
for(auto g : gmp[q.first]) gmp[r[i]].insert(g);
break; }}
else{
for(auto g : fmp[temp]){
gmp[r[i]].insert(g); }
break; }}}}}
if(r[r.size()-1]>='A'&&r[r.size()-1]<='Z'){
for(auto g : gmp[q.first]) gmp[r[i]].insert(g); }}}}
cout<<'\n';
cout<<"FOLLOW: "<<'\n';
for(auto q :
gmp){ string
ans = ""; ans +=
q.first; ans += "
= {";
for(char r :
q.second){ ans += r;
ans += ','; }
ans.pop_back();
ans+="}";
cout<<ans<<'\n'; }
return 0;
}
Output:
PRACTICAL - 11

Aim: Write a Program for implementation of LALR Parser.


Code:
#include <iostream>
#include <sstream>
#include <cctype>
#include <deque>
#include <stack>
#include <vector>
struct Token{
enum
TokenType{ E
ND, INTEGER,
PLUS,
MINUS, } type;
long intValue;
Token(TokenType type=END):type(type),intValue(0){}
Token(long val):type(INTEGER),intValue(val){}
Token(char character){
//...}};
class NonTerminal{
enum
NonTerminalType{ termi
nal,
expr, } type;
NonTerminal *trunk;
std::vector<NonTerminal> branches;
bool reduced;
public:
Token leaf;
private:
void
reduce_terminal(){ t
his->reduced=1;

switch (this-
>leaf.type){ case
Token::INTEGER:
this->type=expr; }}
void reduce_expr(){
if (!this->branches.size())
return;
if (this->branches.size()<3)
this->leaf=this->branches[0].leaf;
else{
this->leaf.type=Token::INTEGER;
switch (this-
>branches[1].leaf.type){
case Token::PLUS:
this->leaf.intValue=this->branches[0].leaf.intValue+this-
>branches[2].leaf.intValue;
break;
case Token::MINUS:
this->leaf.intValue=this->branches[0].leaf.intValue-this-
>branches[2].leaf.intValue;
break;
default:; }}
this->reduced=1;
this->branches.clear();}
public:
NonTerminal(NonTerminal
*trunk=0){ this->type=expr;
this->trunk=trunk;
this->reduced=0; }
NonTerminal(const Token &token,NonTerminal
*trunk=0){ this->leaf=token;
this->type=terminal;
this->trunk=trunk;
this->reduced=0; }
void set(const Token
&token){ this->leaf=token;

this->type=terminal;
this->trunk=trunk;
this->reduced=0; }
void push(const Token
&token){ if (this-
>type==terminal)
return;
this->branches.push_back(NonTerminal(token)); }
NonTerminal *newBranch(const Token &token){
this->branches.push_back(NonTerminal(this));
return &this->branches.back();}
bool isComplete(){
if (this->type==terminal)
return 1;
if (!this->branches.size())
return 0;
for (unsigned a=0;a<this->branches.size();a++)
if (this->branches[a].type!=terminal && !this->branches[a].reduced)
return 0;
switch (this-
>branches.size()){ case 1:
return this->branches[0].leaf.type==Token::INTEGER;
case 3:
if (this->branches[0].leaf.type!=Token::INTEGER ||
this->branches[1].leaf.type!=Token::PLUS &&
this->branches[1].leaf.type!=Token::MINUS ||
this->branches[2].leaf.type!=Token::INTEGER)
return 0;
return 1;
default:
return 0; }}
NonTerminal *reduce(){
if (!this->isComplete())
return 0;
switch (this->type){
case terminal:
this->reduce_terminal();
break;
case expr:
this->reduce_expr();
break; }
return this->trunk?this->trunk:this; }};
class Parser{
std::deque<Token> expression;
std::stack<Token> stack;
long result;
unsigned state;
NonTerminal tree,
*current_node;
Token read(std::stringstream &stream){
//(lexer) }
unsigned
run_state(){
Token::TokenType front_token_type;
switch (this->state){
case 0:
front_token_type=this->expression.front().type;
if (front_token_type==Token::INTEGER)
return 3;
if (front_token_type==Token::END)
return 1;
return 2;
case 3:
this->current_node->push(this->expression.front());
this->expression.pop_front();
if (this->current_node->isComplete())
this->current_node=this->current_node->reduce();
front_token_type=this->expression.front().type;
if (front_token_type==Token::PLUS ||
front_token_type==Token::MINUS)

return 4;
if (front_token_type==Token::END)
return 1;
return 2;
case 4:
this->current_node->push(this->expression.front());
this->expression.pop_front();
front_token_type=this->expression.front().type;
if (front_token_type==Token::INTEGER)
return 3;
return 2;
default:
return this->state; }}
//1: continue, 0: accept, -1: abort
int to_state(unsigned n){
this->state=n;
switch (n){
case 1:
return 0;
case 2:
return -1;
default:
return 1; }}
public:
Parser(const std::string
&str){ std::stringstream
stream(str); do
this->expression.push_back(this->read(stream));
while (this->expression.back().type!=Token::END);
this->result=0;
this->state=0;
this->current_node=&this->tree; }
bool eval(long &res){
int ret;
while ((ret=this->to_state(this->run_state()))==1);
if (!ret){
this->tree.reduce();
res=this->tree.leaf.intValue; }
return !ret; }};
int main(){
Parser evaluator("12+3-2");
long res;
std::cout <<evaluator.eval(res)<<std::endl;
std::cout <<res<<std::endl;
return 0;
}
Output:
PRACTICAL - 04

Write a Program to identify whether a given line is a comment or not.


Code:
#include<stdbool.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void isComment(char *line) {
if(strlen(line)>=2 && line[0]=='/' && line[1]=='/') {

printf("It is a single-line comment.");


return;
}
if(strlen(line)>=4 && line[strlen(line)-2]=='*' && line[strlen(line)-1]=='/' &&
line[0]=='/' && line[1]=='*') {
printf("It is a multi-line comment.");
return;
}
printf("It is not a comment.");
return;
}
int main() {
char *line="/*This is a commented line.*/"; isComment(line);
return 0;
}

Output:
PRACTICAL - 05
Write a Program to check whether a given identifier is valid or not.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
int t;
printf("Enter the number of test cases:\n");
scanf("%d",&t);
while(t--){

char string[50];

int count=0,i;
printf("Enter the String: ");
scanf("%s",&string);
if((string[0]>='a'&&string[0]<='z') || (string[0]>='A'&&string[0]<='Z') || (string[0]=='_')
||(string[0]=='$')){

for(i=1;i<=strlen(string);i++) {

if((string[i]>='a'&& string[i]<='z') || (string[i]>='A' && string[i]<='Z') || (string[i]>='0'&&


string[i]<='9') || (string[i]=='_')){
count++; } } }
if(count==(strlen(string)-1)){
printf("Input string is a valid identifier\n");
}else{
printf("Input string is not a valid identifier\n"); }
}
return 0;
}

Output:
PRACTICAL - 06

Write a Program to recognize strings under ‘a’, ‘a*b+’, ‘abb’.


Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(void){
int t;
printf("Enter the number of test cases:\n");
scanf("%d",&t);
while(t--){

char s[20],c;

int state=0,i=0;
printf("\n Enter a string:");
scanf("%s",&s);
while(s[i]!='\0'){
switch(state){
case 0: c=s[i++];
if(c=='a') state=1;
else if(c=='b') state=2;
else

state=6; break;
case 1: c=s[i++];

if(c=='a') state=3;
else if(c=='b') state=4;
else

state=6; break;
case 2: c=s[i++];
if(c=='a') state=6;
else if(c=='b') state=2;
else state=6; break;
case 3: c=s[i++];
if(c=='a') state=3;
else if(c=='b') state=2;
else

state=6; break;
case 4: c=s[i++];
if(c=='a') state=6;
else if(c=='b')

state=5; else
state=6; break;
case 5:
c=s[i++];

if(c=='a') state=6;
else if(c=='b') state=2;
else

state=6; break;
case 6:
printf("\n %s is not recognised.",s); exit(0); } }
if(state==1)

printf("\n %s is accepted under rule 'a'\n",s); else


if((state==2)||(state==4))
printf("\n %s is accepted under rule 'a*b+'\n",s); else
if(state==5)
printf("\n %s is accepted under rule 'abb'\n",s);
}
getchar();
return 0;
}

Output:
PRACTICAL - 07
Write a Program to simulate lexical analyser for validating operators.
Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int main(){
int t;
printf("Enter the number of test cases: ");
scanf("%d",&t);
while(t--){
char s[5];
printf("\nEnter any operator: ");
scanf("%s",&s);
switch(s[0]){
case'>':
if(s[1]=='=')
printf("\n Greater than or equal"); else
printf("\n Greater than"); break;
case'<':
if(s[1]=='=')
printf("\n Less than or equal"); else
printf("\nLessthan"); break;
case'=':
if(s[1]=='=')
printf("\nEqual to"); else
printf("\nAssignment"); break;
case'!': if(s[1]=='=')
printf("\nNot Equal"); else
printf("\n Bit Not"); break;
case'&': if(s[1]=='&')
printf("\nLogical AND"); else
printf("\n Bitwise AND"); break;
case'|': if(s[1]=='|')
printf("\nLogical OR"); else
printf("\nBitwise OR"); break;
case'+':
printf("\n Addition"); break;
case'-': printf("\nSubstraction");
break;
case'*':
printf("\nMultiplication"); break;
case'/': printf("\nDivision");
break;
case'%': printf("Modulus");
break;
default: printf("\n Not an operator"); }
} getchar();
return 0;
}

Output:
PRACTICAL - 08

Write a Program for implementation of Operator Precedence Parser.


Code:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
void f(){
printf("Not Operator Precedence grammar\n"); exit(0); }
int main(){
int t;
printf("Enter the number of test cases:\n");
scanf("%d",&t);
while(t--){
char grm[20][20], c; int i, n, j
= 2, flag = 0;

scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%s", grm[i]);
for (i = 0; i < n; i++) { c =
grm[i][2];
while (c != '\0') {
if (grm[i][3] == '+' || grm[i][3] == '-' || grm[i][3] == '*' || grm[i][3] == '/') flag = 1;
else {
flag = 0; f(); }
if (c == '$') { flag = 0;

f(); }
c = grm[i][++j]; } } if (flag
== 1)
printf("Operator Precedence grammar\n");
}
return 0;
}

Output:

You might also like