0% found this document useful (0 votes)
5 views21 pages

Experiment 1

The document contains multiple experiments involving programming tasks related to finite state machines (FSM), including checking for consecutive '1's, validating strings ending with '101', counting '1's and '0's, and converting NDFA to DFA. Each experiment provides C++ code implementations for the specified tasks, along with input and output examples. The document also includes a program for validating well-formed parentheses using a stack.

Uploaded by

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

Experiment 1

The document contains multiple experiments involving programming tasks related to finite state machines (FSM), including checking for consecutive '1's, validating strings ending with '101', counting '1's and '0's, and converting NDFA to DFA. Each experiment provides C++ code implementations for the specified tasks, along with input and output examples. The document also includes a program for validating well-formed parentheses using a stack.

Uploaded by

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

EXPERIMENT:-1

1. Design a Program for creating machine that accepts three consecutive one.

#include <iostream>

#include <string>

// Enumeration for FSM states

enum State {

START,

ONE,

TWO,

THREE,

ACCEPT

};

// Function to check if the input string contains three consecutive '1's

bool hasThreeConsecutiveOnes(const std::string& input) {

State currentState = START;

for (char ch : input) {

switch (currentState) {

case START:

if (ch == '1') {

currentState = ONE;

break;
case ONE:

if (ch == '1') {

currentState = TWO;

} else {

currentState = START;

break;

case TWO:

if (ch == '1') {

currentState = THREE;

} else {

currentState = START;

break;

case THREE:

if (ch == '1') {

currentState = ACCEPT;

} else {

currentState = START;

break;

case ACCEPT:

// Stay in ACCEPT state once reached

return true;

}
}

return currentState == ACCEPT;

int main() {

std::string input;

std::cout << "Enter a binary string: ";

std::cin >> input;

if (hasThreeConsecutiveOnes(input)) {

std::cout << "The string contains three consecutive '1's.\n";

} else {

std::cout << "The string does not contain three consecutive '1's.\n";

return 0;

}
EXPERIMENT:-2

2. Design a Program for creating machine that accepts the string always ending with 101.

#include <iostream>

#include <string>

using namespace std;

// Function to check if a string ends with "101"

bool endsWith101(const string &str) {

// Check if the string has at least 3 characters and ends with "101"

if (str.size() >= 3) {

return str.substr(str.size() - 3) == "101";

return false;

int main() {

string input;

cout << "Enter a string (binary only): ";

cin >> input;

// Validate input: Ensure it only contains '0' and '1'

for (char c : input) {

if (c != '0' && c != '1') {

cout << "Invalid input! Please enter a binary string." << endl;

return 1;

}
// Check if the string ends with "101"

if (endsWith101(input)) {

cout << "The string ends wi…

Input:

110101

Output:

The string ends with '101'


EXPERIMENT:-3

3. Design a Program for Mode 3 Machine.

#include <iostream>

#include <string>

using namespace std;

// Enum for representing states in the FSM

enum State {

START,

S1,

S2,

S3

};

// Function to check if the input string ends with "101" using a Mode 3 FSM

bool isMode3Match(const string &input) {

State currentState = START;

// Process each character in the input string

for (char c : input) {

if (c != '0' && c != '1') {

return false; // Invalid character for binary string

switch (currentState) {

case START:

currentState = (c == '1') ? S1 : START;

break;

case S1:
currentState = (c == '0') ? S2 : S1;

break;

case S2:

currentState = (c == '1') ? S3 : START;

break;

case S3:

currentState = (c == '0') ? S2 : S1;

break;

// Accept if the final state is S3

return currentState == S3;

int main() {

string input;

cout << "Enter a binary string: ";

cin >> input;

// Validate input and check if it matches the Mode 3 machine

if (isMode3Match(input)) {

cout << "The string is accepted by the Mode 3 machine (ends with '101')." << endl;

} else {

cout << "The string is not accepted by the Mode 3 machine." << endl;

return 0;
}
EXPERIMENT:-4

4. Design a program for accepting decimal number divisible by 2.

#include <iostream>

#include <string>

using namespace std;

// Function to check if a decimal number is divisible by 2

bool isDivisibleBy2(const string &number) {

// Validate input: Ensure it only contains digits

for (char c : number) {

if (!isdigit(c)) {

return false; // Invalid input if it contains non-digit characters

// Check divisibility by 2 (last digit must be even)

char lastDigit = number[number.size() - 1];

return (lastDigit == '0' || lastDigit == '2' || lastDigit == '4' || lastDigit == '6' || lastDigit == '8');

int main() {

string input;

cout << "Enter a decimal number: ";

cin >> input;

// Check if the input is divisible by 2

if (isDivisibleBy2(input)) {

cout << "The number is divisible by 2." << endl;

} else {
cout << "The number is not divisible by 2." << endl;

return 0;

Input:

124

Output:

The number is divisible by 2


EXPERIMENT:-5

5. Design a program for creating a machine which accepts string having equal no. of 1’s and 0’s.

#include <iostream>

#include <string>

using namespace std;

// Function to check if a string has an equal number of '1's and '0's

bool hasEqualOnesAndZeros(const string &input) {

int countOnes = 0;

int countZeros = 0;

// Iterate through the string and count '1's and '0's

for (char c : input) {

if (c == '1') {

countOnes++;

} else if (c == '0') {

countZeros++;

} else {

// Invalid character (not '0' or '1')

return false;

// Check if the counts are equal

return countOnes == countZeros;

int main() {

string input;
cout << "Enter a binary string: ";

cin >> input;

// Check if the string has equal numbers of '1's and '0's

if (hasE…
EXPERIMENT:-6

6. Design a program for creating a machine which count number of 1’s and 0’s in a given string.

#include <iostream>

#include <string>

using namespace std;

void countOnesAndZeros(const string& input) {

int ones = 0, zeros = 0;

// Iterate through the string and count '1's and '0's

for (char c : input) {

if (c == '1') {

ones++;

} else if (c == '0') {

zeros++;

// Output the results

cout << "Number of 1's: " << ones << endl;

cout << "Number of 0's: " << zeros << endl;

int main() {

string input;

// Get input string from the user

cout << "Enter a binary string: ";


cin >> input;

// Call the function to count ones and zeros

countOnesAndZeros(input);

return 0;

Output :

Enter a binary string: 1010101001

Number of 1's: 5

Number of 0's: 4
EXPERIMENT:-7

7. Design a Program to convert NDFA to DFA.

#include <iostream>

#include <vector>

#include <set>

#include <map>

#include <queue>

using namespace std;

// Define the NDFA structure

class NDFA {

public:

int n; // number of states in NDFA

int m; // number of input symbols

vector<set<int>> transitions; // transition function (state, symbol) -> set of states

set<int> acceptingStates; // accepting states

int startState; // start state

};

// Define the DFA structure

class DFA {

public:

vector<set<int>> transitions; // transition function (state, symbol) -> state

set<int> acceptingStates; // accepting states

int startState; // start state

map<set<int>, int> stateMap; // maps the set of NDFA states to a unique DFA state index
};

// Function to compute epsilon closure of a set of NDFA states

set<int> epsilonClosure(const NDFA &ndfa, const set<int> &states) {

set<int> closure = states;

queue<int> q;

for (int state : states) {

q.push(state);

while (!q.empty()) {

int state = q.front();

q.pop();

// Check epsilon transitions

for (int nextState : ndfa.transitions[state]) {

if (closure.find(nextState) == closure.end()) {

closure.insert(nextState);

q.push(nextState);

return closure;

// Function to convert NDFA to DFA

DFA convertNDFAtoDFA(const NDFA &ndfa) {

DFA dfa;
queue<set<int>> q;

set<int> startStateClosure = epsilonClosure(ndfa, {ndfa.startState});

q.push(startStateClosure);

// Create a stateMap to assign a unique state to each subset of NDFA states

dfa.stateMap[startStateClosure] = 0;

dfa.startState = 0;

dfa.transitions.push_back(vector<int>(ndfa.m, -1)); // Initialize transition table

while (!q.empty()) {

set<int> currentState = q.front();

q.pop();

// Check if the current set of states contains any accepting state of the NDFA

for (int state : currentState) {

if (ndfa.acceptingStates.find(state) != ndfa.acceptingStates.end()) {

dfa.acceptingStates.insert(dfa.stateMap[currentState]);

break;

// Iterate through each input symbol

for (int symbol = 0; symbol < ndfa.m; symbol++) {

set<int> nextState;

// Calculate next state from the NDFA transition function

for (int state : currentState) {

// Collect all states that the current state can transition to

// under the current symbol (including epsilon transitions)

nextState.insert(ndfa.transitions[state].begin(), ndfa.transitions[state].end());
}

// Get epsilon closure of the next state

nextState = epsilonClosure(ndfa, nextState);

// If the next state is not already in DFA, create a new state

if (dfa.stateMap.find(nextState) == dfa.stateMap.end()) {

dfa.stateMap[nextState] = dfa.transitions.size();

dfa.transitions.push_back(vector<int>(ndfa.m, -1)); // Add a new state

q.push(nextState);

// Set the transition for the current state and symbol

dfa.transitions[dfa.stateMap[currentState]][symbol] = dfa.stateMap[nextState];

return dfa;

// Function to display the DFA

void displayDFA(const DFA &dfa) {

cout << "DFA States: " << endl;

for (const auto &state : dfa.stateMap) {

cout << "{ ";

for (int s : state.first) {

cout << s << " ";

cout << "} -> State " << state.second << endl;

}
cout << "\nDFA Transitions: " << endl;

for (int i = 0; i < dfa.transitions.size(); i++) {

for (int j = 0; j < dfa.transitions[i].size(); j++) {


EXPERIMENT:-8

8. Design a Program to create PDA machine that accept the well-formed parenthesis.

#include <iostream>

#include <stack>

#include <string>

using namespace std;

bool isValidParentheses(const string& input) {

stack<char> s;

// Traverse each character in the input string

for (char ch : input) {

// If it's an opening parenthesis, push it onto the stack

if (ch == '(') {

s.push(ch);

// If it's a closing parenthesis, check if there's a matching opening

else if (ch == ')') {

if (s.empty()) {

// Stack is empty, no matching opening parenthesis

return false;

s.pop(); // Pop the opening parenthesis

// If the character is neither '(' nor ')', reject the string

else {
return false;

// If the stack is empty, all parentheses are matched

return s.empty();

int main() {

string input;

cout << "Enter the string of parentheses: ";

cin >> input;

if (isValidParentheses(input)) {

cout << "The input string has well-formed parentheses." << endl;

} else {

cout << "The input string does not have well-formed parentheses." << endl;

return 0;

Input :

Enter the string of parentheses: (())()

Output :

The input string has well-formed parenthes

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy