Code of TOC
Code of TOC
#include <iostream>
using namespace std;
// Manual stack
char stack[100];
int top = -1;
void push(char symbol) {
stack[++top] = symbol;
}
char pop() {
if(top == -1) {
return '\0';
}
return stack[top--];
}
bool transitionFunction(const string & input) {
int state = 1;
char TOS;
cout << "Tracing PDA computation for input: " << input << endl;
for(char symbol: input) {
if(state == 1) {
push('$'); // Push initial symbol onto the stack
cout << "State 1: Pushed '$' onto the stack. Stack size: " << (top + 1) << endl;
state = 2;
}
if(state == 2 && symbol == '0') {
push('0'); // Push '0' onto the stack
cout << "State 2: Read '0', pushed '0' onto the stack. Stack size: " << (top + 1) << endl;
} else if(state == 2 && symbol == '1') {
TOS = pop(); // Pop '0' for each '1'
if(TOS == '0') {
cout << "State 2: Read '1', popped '0' from the stack. Stack size: " << (top + 1) << endl;
state = 3;
} else {
cout << "State 2: Mismatch detected. Stack top is not '0' or stack is empty. Rejecting string.\n";
return false;
}
} else if(state == 3 && symbol == '1') {
TOS = pop(); // Continue popping '0' for each '1'
if(TOS == '0') {
cout << "State 3: Read '1', popped '0' from the stack. Stack size: " << (top + 1) << endl;
} else {
cout << "State 3: Mismatch detected. Stack top is not '0' or stack is empty. Rejecting string.\n";
return false;
}
} else if(state == 2 || state == 3) {
cout << "Invalid symbol detected: '" << symbol << "'. Rejecting string.\n";
return false;
}
}
TOS = pop(); // Final pop to check if only '$' remains
if(state == 3 && TOS == '$' && top == -1) {
cout << "String accepted. Final stack is empty after popping '$'.\n";
return true;
} else {
cout << "String rejected. Stack is not empty or top is not '$'.\n";
return false;
}
}
int main() {
string input;
cout << "Enter the input string: ";
cin >> input;
transitionFunction(input);
return 0;
}
Output: