Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

IPS ACADEMY INDORE

INSTITUTE OF ENGINEERING & SCIENCE


COMPUTER SCIENCE & ENGINEERING
DEPARTMENT

LAB MANUAL
(2021-22)

Theory of Computation

Name : DEV KUMAR UJJAINI

Year : IIIrd Semester : Vth

Class Roll No. : 67

Enrollment No. : 0808CS203D01


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

CONTENTS

1. Vision Mission of the Institute


2. Vision Mission of the Department
3. PEOs
4. POs
5. COs
6. Content beyond Syllabus.
7. Laboratory Regulations and Safety Rules
8. Index
9. Experiments

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Vision of the Institute

To be the fountainhead of novel ideas & innovations in science & technology &
persist to be a foundation of pride for all Indians.

Mission of the Institute

• To provide value based broad Engineering, Technology and Science where


education in students are urged to develop their professional skills.

• To inculcate dedication, hard work, sincerity, integrity and ethics in building up


overall professional personality of our student and faculty.

1. To inculcate a spirit of entrepreneurship and innovation in passing out students.

• To instigate sponsored research and provide consultancy services in technical,


educational and industrial areas.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Vision of the Department

Attaining global recognition in computer science and engineering education,


research and training to meet the growing needs of the industry and society.

Mission of the Department

Provide quality undergraduate and postgraduate education, in both the theoretical


and applied foundations of computer science, and train students to effectively
apply this education to solve real-world problems, thus amplifying their potential
for lifelong high-quality careers.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Program Education Objectives (PEOs)

1. To prepare students for successful careers in software industry that meet the
needs of Indian and multinational companies.

2. To develop the skills among students to analyze real world problem &
implement with computer engineering solution and in multidisciplinary
projects.

3. To provide students with solid foundation in mathematical, scientific and


engineering fundamentals to solve engineering problems and required to
pursue higher studies.

4. To develop the ability to work with the core competence of computer


science & engineering i.e. software engineering, hardware structure &
networking concepts so that one can find feasible solution to real world
problems.

5. To inseminate in students professional and ethical attitude, effective


communication skills, team work skills, multidisciplinary approach, and an
ability to relate engineering issues to broader social context.

6. To motivate students perseverance for lifelong learning and to introduce


them to professional ethics and codes of professional practice.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Program Outcomes (POs)


PO1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.

PO2. Problem analysis: Identify, formulate, research literature, and analyze


complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.

PO3.Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

PO4. Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid
conclusions.

PO5. Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modeling
to complex engineering activities with an understanding of the limitations.

PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

PO7. Environment and sustainability: Understand the impact of the


professional engineering solutions in societal and environmental contexts, and
demonstrate the knowledge of, and need for sustainable development.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

PO9. Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

PO10. Communication: Communicate effectively on complex engineering


activities with the engineering community and with society at large, such as, being
able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.

PO11. Project management and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these to
one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.

PO12. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Course Outcomes (COs)

1. Explain the basic concepts of switching and finite automata theory & languages.
2. Relate practical problems to languages, automata, computability and complexity.
3. Construct abstract models of computing, check their power to recognize the languages and
analyze the grammar, its types, simplification and normal form.
4. Interpret rigorously formal mathematical methods to prove properties of languages, grammars
and automata.
5. Develop an overview of how automata theory, languages and computation are applicable in
engineering application.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Content Beyond Syllabus -

1. State Machine diagram for ATM.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Laboratory Regulations and Safety Rules

1. Without Prior permission do not enter into the Laboratory.

2. While entering into the LAB students should wear their ID cards.

3. The Students should come with proper uniform.

4. Student should not use mobile phone inside the laboratory.

5. Students should sign in the LOGIN REGISTER before entering into the
laboratory.

6. Students should come with observation and record note book to the
laboratory.

7. Do not change any computer setting.

8. Students should maintain silence inside the laboratory.

9. After completing the laboratory exercise, make sure to SHUTDOWN the


system properly.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

INDEX

S.
Experiment Name Date Grade Signature
No.
Design a Program for creating machine that
1. 06/08/2021
accepts three consecutive one.
Design a Program for creating machine that
2. 13/08/2021
accepts the string always ending with 101.
3. Design a Program for Mode 3 Machine. 27/08/2021
Design a program for accepting decimal number
4. 03/09/2021
divisible by 2.

5. Design a program for creating a machine which


accepts string having equal no. of 1’s and 0’s. 17/09/2021

6. Design a program for creating a machine which


count number of 1’s and 0’s in a given string. 24/09/2021
Design a Program to find 2’s complement of a
7. 01/10/2021
given binary number.
Design a Program which will increment the
8. 08/10/2021
given binary number by 1.
9. Design a Program to convert NDFA to DFA. 22/10/2021
Design a Program to create PDA machine that
10. 29/10/2021
accept the well-formed parenthesis.

Design a PDA to accept WCWR where w is any


11. string and WR is reverse of that string and C is a
Special symbol.

Design a Turing machine that’s accepts the


12.
following language an b n c n where n>0.

Content Beyond Syllabus -

13. State Machine diagram for ATM.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 1
Design a Program for creating machine that accepts three consecutive one.
#include <iostream.h>
#include<string.h>
#include<conio.h>
#include<stdio.h>

void main()
{clrscr();
int i, j;
int state=0;
char a[10];
cout<<"Enter the string to check\n";

gets(a);
int x = strlen(a);

for(i=0; i < x; i++)


{ if(a[i]=='0'&& state==0)
state= 0;

else if(a[i]=='1' && state==0)


state=1;
else if(a[i]=='1' && state==1)
state=2;
else if(a[i]=='1' && state==2)
state=3;

else if(a[i]=='1' && state==3)


state=1;
}

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

if(state==3){
cout<<"Accept";
}else{
cout<<"Not Accept";
}
getch();
}

Output:
Enter the string to check
011101
Not Accept

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is Difference Between Fa’s And Nfa’s. Are They Opposite To Each Other ?

Ans: FA stands for finite automata while NFA stands for non-deterministic finite automata, In FA there
must be a transition for each letter of the alphabet from each state. So in FA number of transitions must
be equal to (number of states * number of letter in alphabet).
While in NFA there may be more than one transition for a letter from a state. And finally every FA is
an NFA while every NFA may be an FA or not.

2. What Is The Difference Between Gt And Gtg ?

Ans: In TG, there are transitions for the strings. While in GTG, one can write whole RE as a transition
from one state to another one.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 2
Design a Program for creating machine that accepts the string always ending with 101.
#include <iostream.h>
#include<string.h>
#include<conio.h>
#include<stdio.h>

void main()
{
clrscr();
int i, j;

char a[10];

cout<<"Enter the string to check\n";


gets(a);
int x=strlen(a);
if(a[x-3]=='1' && a[x-2]=='0' && a[x-1]=='1')
{
cout<<"Valid!";

}
else
{
cout<<"Invalid!";
}
getch();

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Output:
Enter the string to check
011101

Accept

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. How To Create A Re Of A Particular Language?


Ans: Regular expression is used to express the infinite or finite language, these RE are made in such
a way that these can generate the strings of that unique language also for the cross check that the
defined RE is of a specified language that RE should accept all the string of that language and all
language strings should be accepted by that RE.

2. How Diagrams Of Fa’s Are Created?


Ans: It depends upon the question how many states involve in a FA. There is not any formal
procedure to design FA for a language. This ability just improves with time and practice.
Every FA is also a TG but not every TG is FA. In every FA, every state shows transition of all
letters of given alphabet but in any TG it is not must. In TG, we may or may not show all letters
transition according to requirement. We can also show transitions on reading any strings in TGs but
it is not possible in FAs.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 3
Design a Program for Mod 3 Machine.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<process.h>

void main()
{
clrscr();
char a[10];
cout<<"Enter the string";
gets(a);
int x=strlen(a);
for(int i=0;i<x;i++)
{
if(a[i]!='0' && a[i]!='1' && a[i]!=’2’ && a[i]!=’3’ && a[i]!=’4’ && a[i]!=’5’ && a[i]!=’6’ &&
a[i]!=’7’ && a[i]!=’8’ && a[i]!=’9’)
{
cout<<"invalid string";
getch();
exit(0);
}
int state=0;
for(i=0; i < x; i++)

{ if(a[i]=='0' || a[i]==’3’ || a[i]==’6’ || a[i]==’9’ && state==0)


state= 0;
else if(a[i]=='1' || a[i]==’4’ || a[i]==’7’ && state==0)
state=1;
else if(a[i]=='2' || a[i]==’5’ || a[i]==’8’ && state==0)
state=2;

if(a[i]=='0' || a[i]==’3’ || a[i]==’6’ || a[i]==’9’ && state==1)


state= 0;
else if(a[i]=='1' || a[i]==’4’ || a[i]==’7’ && state==1)
state=1;
else if(a[i]=='2' || a[i]==’5’ || a[i]==’8’ && state==1)

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

state=2;
if(a[i]=='0' || a[i]==’3’ || a[i]==’6’ || a[i]==’9’ && state==2)
state= 0;
else if(a[i]=='1' || a[i]==’4’ || a[i]==’7’ && state==2)

state=1;
else if(a[i]=='2' || a[i]==’5’ || a[i]==’8’ && state==2)
state=2;

}
if(state==0)

cout<<"Accept";
else
cout<<"Not Accept";
getch();
}

Output:

Enter the string

0110

Accept

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Difference Between Fa’s ,and Tg’s ?


Ans: There are two or three big differences between FA’s and TG’s.
In FA there can be maximum one initial or starting state while in TG there may be more than one
initial state.
In FA there can be transition for letters only while in TG transitions from a state to another one can
be for strings.
In FA there must be transition from each state for each letter (deterministic) while in TG there may
be no transition for specific letter from a state and there may be more than one path for a string or
letter from a state.

2. What Is The Exact Definition Of Fa ?


Ans: Definition: A Finite automaton (FA), is a collection of the followings
o Finite number of states, having one initial and some (maybe none) final states.
o Finite set of input letters (Ó) from which input strings are formed.
o Finite set of transitions i.e. for each state and for each input letter there is a transition
showing how to move from one state to another.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 4
Design a program for accepting decimal number divisible by 2.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<process.h>

void main()
{
clrscr();
char a[10];
cout<<"Enter the string";
gets(a);
int x=strlen(a);
for(int i=0;i<x;i++)
{
if(a[i]!='0' && a[i]!='1' && a[i]!=’2’ && a[i]!=’3’ && a[i]!=’4’ && a[i]!=’5’ && a[i]!=’6’ &&
a[i]!=’7’ && a[i]!=’8’ && a[i]!=’9’)
{
cout<<"invalid string";
getch();
exit(0);
}
int state=0;
for(i=0; i < x; i++)

{ if(a[i]=='0' || a[i]==’2’ || a[i]==’4’ || a[i]==’6’ || a[i]==’8’ && state==0)


state= 0;
else if(a[i]=='1' || a[i]==’3’ || a[i]==’5’ || a[i]==’7’ || a[i]==’9’ || state==0)
state=1;
else if(a[i]=='0' || a[i]==’2’ || a[i]==’4’ || a[i]==’6’ || a[i]==’8’ && state==1)
state=0;

else if(a[i]=='1' || a[i]==’3’ || a[i]==’5’ || a[i]==’7’ || a[i]==’9’ && state==1)


state=1;
}
if(state==0)
cout<<"Accept";

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

else
cout<<"Not Accept";
getch();
}

Output:

Enter the string

12

Accept

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. How Moore And Mealy Machine Works In Computer Memory What Is Their Importance In
Computing ?
Ans: Mealy & Moore Machines work in computing as incrementing machine & 1’s complement
machine etc. These operations as basic computer operations so these machines are very important.

2. Moore And Mealy Machine?


Ans:
1. In order to run a string on a Mealy or Moore machine, you can take directions from transition
table. Running string on Mealy or Moore machine is similar to running string on a FA. For
example, if want to run abba on the machine, take start from initial state. Check what is the
transition for a, what state it goes. After that check what is the path of b from that state and so
on. In this way you will be able to run whole of the string. Note that there is no final state in
Mealy or Moore machine. So there is no case of acceptance or rejection of string. You just have
to determine what the output is. I hope that will clear your mind for further clarification please
listens to your lecture carefully.
2. The string is taken for the testing purposes. You can take any sort of string and determine its
output using machine.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

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

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<process.h>

void main()
{
clrscr();
char a[10];
cout<<"Enter the string";
gets(a);
int x=strlen(a);
for(int i=0;i<x;i++)
{
if(a[i]!='0' && a[i]!='1')
{
cout<<"invalid string";
getch();
exit(0);
}
}
int c0=0,c1=0;
for(i=0;i<x;i++)
{
if(a[i]=='0')
c0++;
else
c1++;
}
int temp=c0-c1;
if(temp==0)
cout<<"Accept";
else
cout<<"reject" ;
getch();
}

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Output:

Enter the string

100101

Accept

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Difference Between Semiword And Word Please Also Give An Example
Regarding This?
Ans: Word: A word is complete combinations of terminals only e.g. abba or ab or a or null string.
Semiword: A semiword is a string of terminals (may be none) concatenated with exactly one
nonterminal on the right i.e. a semi word, in general, is of the following form (terminal)(terminal) —
—- (terminal)(nonterminal)
For example
aaaaaaB , aabbaaaA , A.

2. What Is The Difference Between Derivation Tree And Total Tree ?


Ans: A Derivation tree is the one that shows how to derive any specific word of the language
described by CFG but Total Language Tree shows all words of the Language described by CFG on
it.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

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

#include <bits/stdc++.h>
using namespace std;

bool isOne(int i)
{
if (i == 1)
return true;
else
return false;
}

int main()
{

int a[] = { 1, 0, 0, 1, 0, 0, 1 };

int n = sizeof(a) / sizeof(a[0]);

int count_of_one = count_if(a, a + n, isOne);

cout << "1's: " << count_of_one << endl;


cout << "0's: " << (n - count_of_one) << endl;

return 0;
}

Output:

1’s: 3
0’s: 4

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Difference Between Concatenation And Intersection Of Two Fa’s Also What Is
The Difference Among Union Of Two Fa’s And Addition Of Them?
Ans: In intersection of two FA’s only those strings are accepted which are independently accepted
by both FA’s, while in concatenation of two FA’s only those strings will be accepted in which
first part of string is accepted by first FA and remaining part of string is accepted by the second
FA.
While taking union of two FA’s one can represent it using + sign. So (FA1 U FA2) and (FA +
FA2) both are same. There is no difference between them.

2. Is It Possible To Make Cfg For Infix And Post-fix Expression’s Using Derivation Tree ?
Ans: Derivation tree is only used to derive words of language that is described by a CFG. Yes, we
can create CFG for languages infix expressions, postfix expressions.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 7
Design a Program to find 2’s complement of a given binary number.

#include <bits/stdc++.h>
using namespace std;

// Returns '0' for '1' and '1' for '0'


char flip(char c) {return (c == '0')? '1': '0';}

void printOneAndTwosComplement(string bin)


{
int n = bin.length();
int i;

string ones, twos;


ones = twos = "";

// for ones complement flip every bit


for (i = 0; i < n; i++)
ones += flip(bin[i]);

twos = ones;
for (i = n - 1; i >= 0; i--)
{
if (ones[i] == '1')
twos[i] = '0';
else
{
twos[i] = '1';
break;
}
}

if (i == -1)
twos = '1' + twos;

cout << "1's complement: " << ones << endl;


cout << "2's complement: " << twos << endl;
}

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

int main()
{
string bin = "1100";
printOneAndTwosComplement(bin);
return 0;
}

Output:

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Difference Between The Strings And The Words Of A Language?
Ans: A string is any combination of the letters of an alphabet where as the words of a language are
the strings that are always made according to certain rules used to define that language.For example
if we take
Alphabet Σ = { a , b } Here a , b are the letters of this alphabet.
As you can see we can make a lot of strings from these letters a and b.
For example a,b,aa,ab,ba,bb,aaa,aab,aba,baa,…………………… and so on.
But when we define a language over this alphabet having no a’s and only odd number ofb’s. Then
the words of this language would have only those strings that have only odd number of b’s and no
a’s.some example words of our defined language are b , bbb , bbbbb , bbbbbbb
,……………………………..and so on.
So we can say that all the words are strings but all the strings may not be the words of a language.
Hence strings are any combination of letters of an alphabet and the words of a language are strings
made according to some rule.

2. What Is The Difference Between An Alphabet And An Element Of A Set. Whether Alphabet
Is An Element Of A Set Or It Is A Set Itself?
Ans: An Alphabet is a set in itself. The elements of an Alphabet are called letters.
For example
Binary Alphabet Σ = {0,1}
Here 0,1 are the letters of binary alphabet.
Binary Alphabet is very important because it the Alphabet used by the computer.
Set of Natural Numbers
N={1,2,3,4,5,…………………………………..}
Here 1,2,3……………………………………. are the elements of set of Natural Numbers.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 8
Design a Program which will increment the given binary number by 1.

#include <bits/stdc++.h>
using namespace std;

int addOne(int x)
{
int m = 1;

// Flip all the set bits until we find a 0


while( x & m )
{
x = x ^ m;
m <<= 1;
}

// flip the rightmost 0 bit


x = x ^ m;
return x;
}

int main()
{
cout<<addOne(13);
return 0;
}

Output:

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Concept Of Valid And Invalid Alphabets ?


Ans: While defining an alphabet of letters consisting of more than one symbols, no letter should be
started with any other the letter of the same alphabet i.e. one letter should not be the prefix of
another. However, a letter may be ended in the letter of same alphabet i.e. one letter may be the
suffix of another.
Σ= { a , b } ( Valid Alphabet)
Σ= { a , b , cd } ( Valid Alphabet)
Σ= { a , b , ac } ( Invalid Alphabet)

2. What Is Non-determinism And Determinism And What Is The Difference Between Them ?
Ans: Determinism means that our computational model (machine) knows what to do for every possible
inputs. Non determinism our machine may or may not know what it has to do on all possible inputs.
As you can conclude from above definition that Non-Deterministic machine can not be implemented (
used ) on computer unless it is converted in Deterministic machine.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 9
Design a Program to convert NDFA to DFA.

#include <stdio.h>
#include <string.h>
#define STATES 50
struct Dstate
{
char name;
char StateString[STATES+1];
char trans[10];
int is_final;
}
Dstates[50];
struct tran
{
char sym;
int tostates[50];
int notran;
};
struct state
{
int no;
struct tran tranlist[50];
};
int stackA[100],stackB[100],C[100],Cptr=-1,Aptr=-1,Bptr=-1;
struct state States[STATES];
char temp[STATES+1],inp[10];
int nos,noi,nof,j,k,nods=-1;
void pushA(int z)
{
stackA[++Aptr]=z;
}
void pushB(int z)
{
stackB[++Bptr]=z;
}
int popA()
{
return stackA[Aptr--];
}
void copy(int i)
{
char temp[STATES+1]=" ";
int k=0;

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Bptr=-1;
strcpy(temp,Dstates[i].StateString);
while(temp[k]!='\0')
{
pushB(temp[k]-'0');
k++;
}
}
int popB()
{
return stackB[Bptr--];
}
int peekB()
{
return stackA[Bptr];
}
int peekA()
{
return stackA[Aptr];
}
int seek(int arr[],int ptr,int s)
{
int i;
for(i=0;i<=ptr;i++)
{
if(s==arr[i])
return 1;
}
return 0;
}
void sort()
{
int i,j,temp;
for(i=0;i<Bptr;i++)
{
for(j=0;j<(Bptr-i);j++)
{
if(stackB[j]>stackB[j+1])
{
temp=stackB[j];
stackB[j]=stackB[j+1];
stackB[j+1]=temp;
}
}
}
}

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

void tostring()
{
int i=0; sort();
for(i=0;i<=Bptr;i++)
{
temp[i]=stackB[i]+'0';
}
temp[i]='\0';
}
void display_DTran()
{
int i,j;
printf("\n\t\t DFA Transition Table ");
printf("\n\t\t -------------------- ");
printf("\nStates\tString\tInputs\n ");
for(i=0;i<noi;i++)
{
printf("\t%c",inp[i]);
}
printf("\n \t----------");
for(i=0;i<nods;i++)
{

if(Dstates[i].is_final==0)
printf("\n%c",Dstates[i].name);
else
printf("\n*%c",Dstates[i].name);

printf("\t%s",Dstates[i].StateString);
for(j=0;j<noi;j++)
{
printf("\t%c",Dstates[i].trans[j]);
}
}
printf("\n");
}
void move(int st,int j)
{
int ctr=0;
while(ctr<States[st].tranlist[j].notran)
{
pushA(States[st].tranlist[j].tostates[ctr++]);
}
}
void lambda_closure(int st)

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

{
int ctr=0,in_state=st,curst=st,chk;
while(Aptr!=-1)
{
curst=popA();
ctr=0;
in_state=curst;
while(ctr<=States[curst].tranlist[noi].notran)
{
chk=seek(stackB,Bptr,in_state);
if(chk==0)
pushB(in_state);
in_state=States[curst].tranlist[noi].tostates[ctr++];
chk=seek(stackA,Aptr,in_state);
if(chk==0 && ctr<=States[curst].tranlist[noi].notran)
pushA(in_state);
}
}
}
main()
{
int final[20],start,fin=0,i;
char c,ans,st[20];
printf("\nEnter no. of states in NFA : ");
scanf("%d",&nos);
for(i=0;i<nos;i++)
{
States[i].no=i;
}
printf("\nEnter the start state : ");
scanf("%d",&start);
printf("Enter the no. of final states : ");
scanf("%d",&nof);
printf("\nEnter the final states : \n");
for(i=0;i<nof;i++)
scanf("%d",&final[i]);
printf("\nEnter the no. of input symbols : ");
scanf("%d",&noi);
c=getchar();
printf("\nEnter the input symbols : \n ");
for(i=0;i<noi;i++)
{
scanf("%c",&inp[i]);
c=getchar();
}
inp[i]='e';

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

printf("\nEnter the transitions : (-1 to stop)\n");


for(i=0;i<nos;i++)
{
for(j=0;j<=noi;j++)
{
States[i].tranlist[j].sym=inp[j];
k=0; ans='y';
while(ans=='y')
{
printf("move(%d,%c) : ",i,inp[j]);
scanf("%d",&States[i].tranlist[j].tostates[k++]);
if(States[i].tranlist[j].tostates[k-1]==-1)
{
k--;ans='n';
break;
}
}
States[i].tranlist[j].notran=k;
}
}
//Conversion
i=0;nods=0;fin=0;
pushA(start);
lambda_closure(peekA());
tostring();
Dstates[nods].name='A';
nods++;
strcpy(Dstates[0].StateString,temp);
while(i<nods)
{
for(j=0;j<noi;j++)
{
fin=0; copy(i);
while(Bptr!=-1)
{
move(popB(),j);
}
while(Aptr!=-1)
lambda_closure(peekA());
tostring();
for(k=0;k<nods;k++)
{
if((strcmp(temp,Dstates[k].StateString)==0))
{

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Dstates[i].trans[j]=Dstates[k].name;
break;
}
}
if(k==nods)
{
nods++;
for(k=0;k<nof;k++)
{
fin=seek(stackB,Bptr,final[k]);
if(fin==1)
{
Dstates[nods-1].is_final=1;
break;
}
}
strcpy(Dstates[nods-1].StateString,temp);
Dstates[nods-1].name='A'+nods-1;
Dstates[i].trans[j]=Dstates[nods-1].name;
}
}
i++;
}
display_DTran();
}

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is Difference Between Fa’s And Nfa’s. Are They Opposite To Each Other ?
Ans: FA stands for finite automata while NFA stands for non-deterministic finite automata, In FA there
must be a transition for each letter of the alphabet from each state. So in FA number of transitions must
be equal to (number of states * number of letter in alphabet).
While in NFA there may be more than one transition for a letter from a state. And finally every FA is
an NFA while every NFA may be an FA or not.

2. What Is The Concept Of The Union Of Fa’s ?


Ans: When we take Union of two FA’s it means that resultant FA’s should accept all the words that
were accepted by the two FA’s individually. It is like taking union of two sets, the resultant set contain
members of both sets.
For example
Let A ={1,3,5,7,9}
and
B = {0,2,4,6,8,10}
then, A U B = { 0,1,2,3,4,5,6,7,8,9,10 }
you can see that A U B contain elements of both sets similar is the case with FA’s.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 10
Design a Program to create PDA machine that accept the well-formed parenthesis.

#include<bits/stdc++.h>
using namespace std;

// function to check if paranthesis are balanced


bool areParanthesisBalanced(string expr)
{
stack<char> s;
char x;

// Traversing the Expression


for (int i=0; i<expr.length(); i++)
{
if (expr[i]=='('||expr[i]=='['||expr[i]=='{')
{
// Push the element in the stack
s.push(expr[i]);
continue;
}

if (s.empty())
return false;

switch (expr[i])
{
case ')':

// Store the top element in a


x = s.top();
s.pop();
if (x=='{' || x=='[')
return false;
break;

case '}':

// Store the top element in b


x = s.top();
s.pop();
if (x=='(' || x=='[')
return false;
break;

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

case ']':

// Store the top element in c


x = s.top();
s.pop();
if (x =='(' || x == '{')
return false;
break;
}
}

// Check Empty Stack


return (s.empty());
}

int main()
{
string expr = "{()}[]";

if (areParanthesisBalanced(expr))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}

Output:

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What Is The Uses Of Push Down Automata In Computing ?


Ans: PDA is just an enhancement in FAs. i.e Memory is attached with machine that recognizes
some language. FA is basic structure for most advanced electronic machines such as computer etc.

2. What Is Difference Between Push Down Stack And Push Down Store ?
Ans: No difference at all. Both terms are used to describe memory structure attached with FAs to
store some characters in it.

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 11
Design a PDA to accept WCWR where w is any string and WR is reverse of that string and C is a
Special symbol.

#include <stdio.h>
#include <string.h>
void isPalindrome(char str[])
{
// Start from leftmost and rightmost corners of str
int l = 0;
int h = strlen(str) - 1;

// Keep comparing characters while they are same


while (h > l)
{
if (str[l++] != str[h--])
{
printf("%s is Not Palindrome", str);
return;
}
}
printf("%s is palindrome", str);
}

int main()
{
isPalindrome("abba");
isPalindrome("abbccbba");
isPalindrome("geeks");
return 0;
}

Output:

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What is the basic Structure of PDA?


Ans: A pushdown automaton is a process that includes a context-free grammar in a same way we
design DFA for a regular grammar. A DFA includes a finite amount of information, but a PDA
includes an infinite amount of information.
Generally a pushdown automaton is −
"Finite state machine" + "a stack"

2. What are the Terminologies Related to PDA?

Ans: Instantaneous Description


The instantaneous description (ID) of a PDA is marked as a triplet (q, w, s) where
3. q is the state
4. w is unconsumed input
5. s is the stack contents

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 12
Design a Turing machine that’s accepts the following language a n bn cn where n>0.

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
int main()
{
char a[50];
int i,j,k,len;
cout<<"Enter the string to check\n"; //input the string
cin>>a;
if(strlen(a)%3!=0) //if string length is not multiple of 3 , reject it
{
cout<<"Not accepted\n";
exit(0);
}
len=strlen(a)/3; //len= length of the input string
for(i=0;i<len;i++)
{
if(a[i]!='a')
{
cout<<"Not accepted\n";
exit(0);
}
}
for(j=i;j<i+len;j++) //checks if next len/3 characters are ‘b’
{
if(a[j]!='b')
{
cout<<"Not accepted\n";
exit(0);
}
}
for(k=j;k<j+len;k++) //checks if next len/3 characters are ‘c’
{
if(a[k]!='c')
{
cout<<"Not accepted";
exit(0);
}
}
/*if all conditions are satisfied, it shows that input is accepted*/
cout<<"Accepted\n";

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

return 0;
}

Output:

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Viva Questions:

1. What is turing machine?


Ans: A Turing Machine is considered as a supportive device which supports languages recursively
enumerable set) created by type 0 grammars. It was introduced in 1936 by Alan Turing.

Definition
A Turing Machine (TM) is a mathematical model it includes an infinite length tape categorized into
cells along with the given input. It includes a head which is used to read t he input tape. Here a state
register saves the state of the Turing machine. Once you read an input symbol, it will exchange with
another symbol and it changes the internal state. At the same time it moves from one cell to the right or
left. Once the TM reaches the final state, then the input string is accepted, otherwise rejected.
A TM is usually explained as a 7-tuple (Q, X, ∑, δ, q0, B, F) where −
• Q is a finite set of states
• X is the tape alphabet
• ∑ is the input alphabet
• δ is a transition function; δ : Q × X → Q × X × {Left_shift, Right_shift}.
• q0 is the initial state
• B is the blank symbol
• F is the set of final states

2. Time and Space Complexity of a Turing Machine.

Ans: While a turning machine refers to the time complexity to calculate the number of times the
tape moves when the machine started to provide some input symbols and the space complexity
while writing the number of cells of the tape written.

Time complexity all reasonable functions −

T(n) = O(n log n)


TM's space complexity −
S(n) = O(n)

5th SEM THEORY OF COMPUTATION 2021-22


IPS ACADEMY, INSTITUTE OF ENGINEERING AND SCIENCE- INDORE

Experiment No. 13
State Machine diagram for ATM.

State machine diagram is a behavior diagram which shows discrete behavior of a part of designed
system through finite state transitions. Behavioral state machine is specialization of behavior
and is used to specify discrete behavior of a part of designed system through finite state transitions.
The state machine formalism used in this case is an object -based variant of Harel statecharts.
Behavior is modeled as a traversal of a graph of state nodes connected with transitions. Transitions
are triggered by the dispatching of series of events. During the traversal, the state machine could also
execute some activities.
Behavioral state machine could be owned by behavioral classifier which is called its context. The
context defines which signal and call triggers are defined for this state machine, and which attributes
and operations are available in activities of the state machine. Signal triggers and call triggers for the
state machine are defined according to the receptions and operations of this classifier.
State machine may have an associated behavioral feature (specification) and be the method of this
behavioral feature. In this case the state machine specifies the behavior of this behavioral feature. The
parameters of the state machine match the parameters of the behavioral feature and provide the means
for accessing the behavioral feature parameters within the state machine.
The event pool for the state machine is the event pool of the instance according to the behaviored
context classifier, or the classifier owning the behavioral feature for which the state machine is a
method.
The context classifier of the method state machine of a behavioral feature must be the classifier that
owns the behavioral feature. A state machine without a context classifier may use triggers that are
independent of receptions or operations of a classifier, i.e., either just signal triggers or call triggers
based upon operation template parameters of the (parameterized) state machine.
The association between a state machine and its context classifier or behavioral feature does not have a
special notation.
State machine could be rendered in the frame labeled as state machine or stm in abbreviated form. The
content area of the frame is usually state machine itself but in general it could contain other kinds of
UML diagrams.

Service

High level behavioral state machine for bank ATM

5th SEM THEORY OF COMPUTATION 2021-22


Knowledge, Skills, Values

IPS ACADEMY
16 Collages, 71 Courses, 51 Acre Campus

ISO 9001: 2008 Certified

Knowledge Village
Rajendra Nagar
A. B. Road Indore
452012(M.P.) India
Ph: 0731-4014601-604 Mo: 07746000161
E Mail: office.ies@ipsacademy.org
Website: ies.ipsacademy.org & www.ipsacademy.org
1

You might also like