0% found this document useful (0 votes)
11 views10 pages

CD File Manjot 4 To 9 PDF

The document contains multiple C++ programs aimed at recognizing strings based on specific patterns, validating identifiers, simulating lexical analyzers, and implementing predictive parsers. Each program is structured with functions to perform specific checks and outputs results based on user input. The document also includes objectives and outputs for each practical exercise.
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)
11 views10 pages

CD File Manjot 4 To 9 PDF

The document contains multiple C++ programs aimed at recognizing strings based on specific patterns, validating identifiers, simulating lexical analyzers, and implementing predictive parsers. Each program is structured with functions to perform specific checks and outputs results based on user input. The document also includes objectives and outputs for each practical exercise.
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/ 10

Practical No -4

Objective: Write a Cpp program to recognize strings under 'a', 'a*b+', 'abb'
Program:

#include <iostream>
#include <string>

using namespace std;

// Function to check if the string matches 'a'


bool matches_a(const string& str) {
return str == "a";
}

// Function to check if the string matches 'a*b+'


bool matches_a_star_b_plus(const string& str) {
size_t i = 0;

// Match 'a*'
while (i < str.length() && str[i] == 'a') {
i++;
}

// Match 'b+'
if (i == str.length() || str[i] != 'b') {
return false; // No 'b' found or invalid character
}
while (i < str.length() && str[i] == 'b') {
i++;
}

// Ensure no extra characters


return i == str.length();
}

// Function to check if the string matches 'abb'


bool matches_abb(const string& str) {
return str == "abb";
}

// Function to determine which pattern a string matches


void recognize_string(const string& str) {
if (matches_a(str)) {
cout << "The string \"" << str << "\" matches the pattern 'a'." << endl;
} else if (matches_a_star_b_plus(str)) {
cout << "The string \"" << str << "\" matches the pattern 'a*b+'." << endl;
} else if (matches_abb(str)) {
cout << "The string \"" << str << "\" matches the pattern 'abb'." << endl;
} else {
cout << "The string \"" << str << "\" does not match any pattern." << endl;
}
}

Manjot Singh 2220979 D1


// Main function
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
recognize_string(str);
return 0;
}

Output:

For this Particular Input :- Output:-

Manjot Singh 2220979 D1


Practical No: 5

Objective: Write a Cpp program to test whether a given identifier is valid or not.

Program:

#include <iostream>
#include <string>
#include <cctype>
#include <unordered_set>

using namespace std;

// Function to check if a string is a reserved keyword in C++


bool isKeyword(const string& str) {
// List of some common C++ reserved keywords
unordered_set<string> keywords = {
"auto", "break", "case", "char", "class", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "inline", "int", "long", "namespace", "new", "operator", "private",
"protected", "public", "return", "short", "signed", "sizeof", "static",
"struct", "switch", "template", "this", "throw", "try", "typedef",
"union", "unsigned", "using", "virtual", "void", "volatile", "while"
};
return keywords.find(str) != keywords.end();
}

// Function to check if a given identifier is valid


bool isValidIdentifier(const string& identifier) {
// Empty string is not a valid identifier
if (identifier.empty()) {
return false;
}

// Check if the first character is a letter or underscore


if (!isalpha(identifier[0]) && identifier[0] != '_') {
return false;
}

// Check the rest of the characters


for (size_t i = 1; i < identifier.length(); ++i) {
if (!isalnum(identifier[i]) && identifier[i] != '_') {
return false;
}
}

// Check if it is a reserved keyword


if (isKeyword(identifier)) {
return false;
}

return true;
}

Manjot Singh 2220979 D1


int main() {
string identifier;

cout << "Enter an identifier: ";


cin >> identifier;

if (isValidIdentifier(identifier)) {
cout << "\"" << identifier << "\" is a valid identifier." << endl;
} else {
cout << "\"" << identifier << "\" is not a valid identifier." << endl;
}

return 0;
}

Output:

For this Particular Input :- Output:-

Manjot Singh 2220979 D1


Practical No: 6

Objective: Write a CPP Program to stimulate the lexical analyzer for validating operator

Program:
#include <iostream>
#include <string>
#include <cctype>
#include <unordered_set>
using namespace std;
bool isOperator(char c) {

// List of valid operators


unordered_set<char> operators = {'+', '-', '*', '/', '=', '<', '>', '&', '|', '%'};
return operators.find(c) != operators.end();
}
bool isOperand(char c) {
return isalpha(c) || isdigit(c);
}
// Function to simulate the lexical analyzer
void lexicalAnalyzer(const string& input) {

bool valid = true;


for (int i = 0; i < input.length(); i++) {

char currentChar = input[i];


// Check for operators
if (isOperator(currentChar)) {

cout << "Operator found: " << currentChar << endl;


}
// Check for operands (numbers or identifiers)
else if (isOperand(currentChar)) {
cout << "Operand found: " << currentChar << endl;
}
/ / C h e c k f o r i n v a l i d c h a r a c t e r s ( a n y t h i n g
e l s e i f ( ! i s s p a c e ( c u r r e n t C h a r ) ) {
cout << "Error: Invalid character encountered: " << currentChar << endl;
valid = false;
}
}
} i f ( v a l i d ) {
i n t
m acout i << "Lexical analysis completed successfully." << endl;
n }( else
) {
{ cout << "Lexical analysis encountered errors." << endl;
}

string input;
cout << "Enter an expression to analyze: ";
getline(cin, input);

// Perform lexical analysis


lexicalAnalyzer(input);

return 0;
}

Output:-

Manjot Singh 2220979 D1


Practical No: 7

Objective: Implement the lexical analyzer using JLex, flex or other lexical analyzer generating tools.

Program:
#include<string.h>
#include<conio.h>
#include<ctype.h>
#include<stdio.h>
int main()
{
FILE *f1;
char c,str[10];
int lineno=1,num=0,i=0;
printf("\nEnter the c program\n");
f1=fopen("input.txt","w");
while((c=getchar())!=EOF)
putc(c,f1);
fclose(f1);
f1=fopen("input.txt","r");
while((c=getc(f1))!=EOF)
{
if(isdigit(c))
{
num=c-48;
c=getc(f1);
while(isdigit(c))
{
num=num*10+(c-48);
c=getc(f1);
}
printf("%d is a number \n",num);
ungetc(c,f1);
}
else if(isalpha(c))
{
str[i++]=c;
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
str[i++]=c;
c=getc(f1);
}
str[i++]='\0';
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("%s is a keyword\n",str);
else
printf("%s is a identifier\n",str);
ungetc(c,f1);
i=0;
}
else if(c==' '||c=='\t')
printf("\n");
else if(c=='\n')
lineno++;
else
printf("%c is a special symbol\n",c);
}
printf("Total no. of lines are: %d\n",lineno);
fclose(f1);
getch();
return 0;
}

Output:-

Manjot Singh 2220979 D1


Practical No: 9A

Objective: Write a CPP Program to stimulate the lexical analyzer for validating operator

Program:
#include <iostream> #include <vector> #include <stack> #include
<unordered_map> #include <string> using namespace std; class LL1Parser
{ public: // Define the grammar rules as a map of non-terminal ->
production rules unordered_map<string, vector<string>> grammar;
unordered_map<string, unordered_map<char, string>> parseTable;

// Constructor to initialize the grammar and the parsing table


LL1Parser() {
// Grammar: S -> A B, A -> a, B -> b | ε grammar["S"] = {"A
B"}; grammar["A"] = {"a"}; grammar["B"] = {"b", "ε"}; //
Construct the LL(1) parsing table parseTable["S"]['a'] = "A B";
parseTable["A"]['a'] = "a"; parseTable["B"]['b'] = "b";
parseTable["B"]['a'] = "ε"; // B can go to epsilon when 'a' comes

}
b o o l p a r s e ( s t r i n g i n p u t ) {

stack<string> parseStack;
parseStack.push("$"); // End of input marker
parseStack.push("S"); // Start symbol
int i = 0;
input += '$'; // Append end-of-input marker
cout << "Parsing steps:" << endl;
while (!parseStack.empty()) {

string top = parseStack.top();


parseStack.pop();
char currentChar = input[i];
cout << "Stack: ";
stack<string> tempStack = parseStack;
while (!tempStack.empty()) {

cout << tempStack.top() << " ";


currentChar << endl;
tempStack.pop();
}
c o u t < < e n d l ;
i f ( t o p = = " $ " & & c u r r e n t C h a r = = ' $ ' ) {

cout << "Parsing successful!" << endl;


return true;
}
e l s e i f ( t o p = = s t r i n g ( 1 , c u r r e n t C h a r ) ) {
cout << "Match: " << currentChar << endl;
i++; // Consume the input symbol
}
e l s e i f ( i s N o n T e r m i n a l ( t o p ) ) {
// Look up the production in the table
string production = parseTable[top][currentChar];
if (production == "") {
cout << "Error: No production for " << top << " on input " <<
return false;
}

Manjot Singh 2220979 D1


cout << "Applying production: " << top << " -> " << production
<< endl; if (production != "ε")
{ // Push the production symbols in reverse order
for (int j = production.length() - 1; j >= 0; j--) {
parseStack.push(string(1, production[j]));
}
}
}
else { cout << "Error: Unexpected symbol " << top << endl;
return false;
}
}
return false; // Failure if stack is empty and input is not completely
consumed }
private: // Function to check if a symbol is a non-terminal bool
isNonTerminal(string symbol) { return grammar.find(symbol) !=
grammar.end(); } }; int main() { LL1Parser parser; string input;
cout << "Enter input string: "; cin >> input; if (parser.parse(input))
{ cout << "Input string successfully parsed!" << endl; } else { cout
<< "Error parsing the input string!" << endl; } return 0; }

Output:-

Manjot Singh 2220979 D1


Practical No: 8

Objective: Write a Cpp program for implementing the functionality of predictive parser

Program:
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <stack>
using namespace std;
// Function to check if a character is a non-terminal
bool isNonTerminal(char c) {
return c >= 'A' && c <= 'Z';
}
// Function to implement predictive parser
bool predictiveParser(const string &input, const map<char, vector<string>>
&parsingTable) {

stack<char> parseStack;
parseStack.push('$'); // End symbol
parseStack.push('S'); // Start symbol (assumed to be S)

int i = 0; // Pointer for the input string


while (!parseStack.empty()) {
char top = parseStack.top();
char currentInput = input[i];
// If the top of the stack is a terminal symbol or '$' (end of input)
if (top == currentInput) {

parseStack.pop();
i++;
if (currentInput == '$') {
break; // Successfully parsed the entire input
}
}
// If the top of the stack is a non-terminal
{ else if (isNonTerminal(top)) {
// If there is no production rule for the non-terminal and input symbol, error
if (parsingTable.find(top) == parsingTable.end() || parsingTable.at(top).empty())

cout << "Error: No production rule for " << top << " with input " <<
currentInput << endl;
return false;
}
s t r i n g r u l e = " " ;
f o r ( c o n s t s t r i n g & p r o d : p a r s i n g T a b l e . a t
if (prod[0] == currentInput) {
rule = prod;
break;
}
}
i f ( r u l e . e m p t y ( ) ) {
coutcurrentInput
symbol " << << "Error: No
<<matching
endl; rule for non-terminal " << top << " and input
return false;
}
/ / P o p t h e t o p s y m b o l a n d p u s h t h e p r o d u
p a r s e S t a c k . p o p ( ) ;
f o r ( i n t j = r u l e . l e n g t h ( ) - 1 ; j > = 0 ; j - -
if (rule[j] != 'ε') { // If not epsilon (empty)
parseStack.push(rule[j]);
}
}
}

Manjot Singh 2220979 D1


// If the top of the stack is a terminal but doesn't
match the input symbol, it's a syntax error
else { cout << "Error: Unexpected symbol " <<
currentInput << " at position " << i << endl;
return false; } } return true; } int main() { //
Grammar: S -> aA | bB, A -> cS | ε, B -> dS //
Create a parsing table (mapping of non-terminal -
> vector of possible production rules) map<char,
vector<string>> parsingTable; // S productions
parsingTable['S'] = {"aA", "bB"}; // A productions
parsingTable['A'] = {"cS", "ε"}; // B productions
parsingTable['B'] = {"dS"}; // Input string string
input; cout << "Enter the input string: "; cin >>
input; input += '$'; // Add the end symbol to input
// Run the predictive parser if
(predictiveParser(input, parsingTable)) { cout <<
"Input string successfully parsed!" << endl; } else {
cout << "Error in parsing the input string." <<
endl; } return 0; }

Output:-

Manjot Singh 2220979 D1

You might also like