To Check Whether String Belongs To A Grammar or Not: Algorithm
To Check Whether String Belongs To A Grammar or Not: Algorithm
GRAMMAR OR NOT
ALGORITHM
Start.
Declare two character arrays str[],token[] and initialize integer variables a=0,b=0,c,d. Input
the string from the user.
Repeat steps 5 to 12 till str[a] =’\0’.
If str[a] =='(' or str[a] =='{' then token[b] =’4’, b++.
If str[a] ==')' or str[a] =='}’ then token[b] =’5’, b++.
Check if isdigit(str[a]) then repeat steps 8 till isdigit(str[a])
a++.
a--, token[b] =’6’, b++.
If str[a]=='+’ then token[b]='2',b++.
If(str[a]=='*') then token[b]=’3’,b++.
a++.
token[b]='\0';
then print the token generated for the string .
b=0.
Repeat step 22 to 31 till token[b]!='\0'
c=0.
Repeat step 24 to 30 till (token[b]=='6' and token[b+1]=='2' and token[b+2]=='6') or
(token[b]=='6' and token[b+1]=='3'and token[b+2]=='6') or (token[b]=='4' and
token[b+1]=='6' and token[b+2]=='5') or (token[c]!='\0').
token[c]='6';
c++;
Repeat step 27 to 28 till token[c]!='\0'.
token[c]=token[c+2].
c++.
token[c-2]=’\0’.
print token.
b++.
Compare token with 6 and store the result in d.
If d=0 then print that the string is in the grammar.
Else print that the string is not in the grammar.
Stop.
PROGRAM TO CHECK WHEATHER A STRING BELONGS TO A
GRAMMAR OR NOT.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
int a=0,b=0,c;
char str[20],tok[11];
clrscr();
printf("Input the expression = ");
gets(str);
while(str[a]!='\0')
{
if((str[a]=='(')||(str[a]=='{'))
{
tok[b]='4';
b++;
}
if((str[a]==')')||(str[a]=='}'))
{
tok[b]='5';
b++;
}
if(isdigit(str[a]))
{
while(isdigit(str[a]))
{
a++;
}
a--;
tok[b]='6';
b++;
}
if(str[a]=='+')
{
tok[b]='2';
b++;
}
if(str[a]=='*')
{
tok[b]='3';
b++;
}
a++;
}
tok[b]='\0';
puts(tok);
b=0;
while(tok[b]!='\0')
{
if(((tok[b]=='6')&&(tok[b+1]=='2')&&(tok[b+2]=='6'))||((tok[b]=='6')&&(tok[b+1
]=='3')&&(tok[b+2]=='6'))||((tok[b]=='4')&&(tok[b+1]=='6')&&(tok[b+2]=='5'))/*||((tok[b
]!=6)&&(tok[b+1]!='\0'))*/)
{
tok[b]='6';
c=b+1;
while(tok[c]!='\0')
{
tok[c]=tok[c+2];
c++;
}
tok[c]='\0';
puts(tok);
b=0;
}
else
{
b++;
puts(tok);
}
}
int d;
d=strcmp(tok,"6");
if(d==0)
{
printf("It is in the grammar.");
}
else
{
printf("It is not in the grammar.");
}
getch();
}
OUTPUT
Input the expression = (23+)
4625
4625
4625
4625
4625
It is not in the grammar.
ALGORITHM
1. Start
2. For each nonterminal A and terminal a do L(A,a):= false;
3. For each production of the form A->a or A->B do
INSTALL(A,a);
4. While STACK not empty repeat step 5& 6
5. Pop top pair (B,a) from STACK;
6. For each production of the form A->B do
INSTALL(A,a)
7. Stop
1. Start
2. If L(A,a) not present do step 3 and 4.
3 . Make L(A,a)=True
4 . Push (A,a) onto stack
5 . Stop
PROGRAM IS TO CALCULATE LEADING FOR ALL
THE NON-TERMINALS OF THE GIVEN GRAMMAR
#include<conio.h>
#include<stdio.h>
char arr[18][3] =
{
{'E','+','F'},{'E','*','F'},{'E','(','F'},{'E',')','F'},{'E','i','F'},{'E','$','F'},
{'F','+','F'},{'F','*','F'},{'F','(','F'},{'F',')','F'},{'F','i','F'},{'F','$','F'},
{'T','+','F'},{'T','*','F'},{'T','(','F'},{'T',')','F'},{'T','i','F'},{'T','$','F'}, };
E + T
E * T
E ( T
E ) F
E i T
E $ F
F + F
F * F
F ( T
F ) F
F i T
F $ F
T + F
T * T
T ( T
T ) F
T i T
T $ F
PRACTICAL 4
char arr[18][3] =
{
{'E','+','F'},{'E','*','F'},{'E','(','F'},{'E',')','F'},{'E','i','F'},{'E','$','F'},
{'F','+','F'},{'F','*','F'},{'F','(','F'},{'F',')','F'},{'F','i','F'},{'F','$','F'},
{'T','+','F'},{'T','*','F'},{'T','(','F'},{'T',')','F'},{'T','i','F'},{'T','$','F'}, };
char prod[6] = "EETTFF";
char res[6][3]=
{
{'E','+','T'},{'T','\0','\0'},
{'T','*','F'},{'F','\0','\0'},
{'(','E',')'},{'i','\0','\0'}, };
char stack [5][2];
int top = -1;
void main()
{
int i=0,j;
char pro,re,pri=' ';
clrscr();
for(i=0;i<6;++i)
{
for(j=2;j>=0;--j)
{
if(res[i][j]=='+'||res[i][j]=='*'||res[i][j]=='('||res[i][j]==')'||res[i][j]=='i'||res[i][j]=='$')
{
install(prod[i],res[i][j]);
break;
}
else if(res[i][j]=='E' || res[i][j]=='F' || res[i][j]=='T')
{
if(res[i][j-1]=='+'||res[i][j-1]=='*'||res[i][j-1]=='('||res[i][j-
1]==')'||res[i][j-1]=='i'||res[i][j-1]=='$')
{
install(prod[i],res[i][j-1]);
break;
}
}
}
}
while(top>=0)
{
pro = stack[top][0];
re = stack[top][1];
--top;
for(i=0;i<6;++i)
{
for(j=2;j>=0;--j)
{
if(res[i][0]==pro && res[i][0]!=prod[i])
{
install(prod[i],re);
break;
}
else if(res[i][0]!='\0')
break;
}
}
}
for(i=0;i<18;++i)
{
printf("\n\t");
for(j=0;j<3;++j)
printf("%c\t",arr[i][j]);
}
getch();
clrscr();
printf("\n\n");
for(i=0;i<18;++i)
{
if(pri!=arr[i][0])
{
pri=arr[i][0];
printf("\n\t%c -> ",pri);
}
if(arr[i][2] =='T')
printf("%c ",arr[i][1]);
}
getch();
}
OUTPUT
E + T
E * T
E ( F
E ) T
E i T
E $ F
F + F
F * F
F ( F
F ) T
F i T
F $ F
T + F
T * T
T ( F
T ) T
T i T
T $ F
E -> + * ) i
F -> ) i
T -> * ) i
PRACTICAL 5
PROGRAM FOR COMPUTATION OF FIRST
ALGORITHM
To compute FIRST(X) for all grammar symbols x, apply the following rules until no more
terminals can be added to any FIRST set.
if(p[i][j]==t[k])
{
first[i][j]=t[k];
first[i][j+1]='$';
f=1;
break;
}
else if(p[i][j]==nt[k])
{
first[i][j]=first[k][j];
if(first[i][j]=='e')
continue;
first[i][j+1]='$';
f=1;
break;
}
}
}
}
for(i=0;i<nont;i++)
{
printf("\n\nThe first of %c -> ",first[i][0]);
for(j=1;first[i][j]!='$';j++)
{
printf("%c\t",first[i][j]);
}
}
getch();
}
OUTPUT
Enter the no. of Non-terminals in the grammer:3
Enter the production for E ( End the production with '$' sign ) :a+s$
Enter the production for R ( End the production with '$' sign ) :e$
Enter the production for T ( End the production with '$' sign ) :Rs$
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[200],ch;
int a=0,space=0,newline=0;
clrscr();
printf("\n enter a string(press escape to quit entering):");
ch=getche();
while((ch!=27) && (a<199))
{
str[a]=ch;
if(str[a]==' ')
{
space++;
}
if(str[a]==13)
{
newline++;
printf("\n");
}
a++;
ch=getche();
}
printf("\n the number of lines used : %d",newline+1);
printf("\n the number of spaces used is : %d",space);
getch();
}
OUTPUT
enter a string(press escape to quit entering):hello!
how r u?
Do you like prog. in compiler?
DELETION
POP(item)
1. If (top = - 1)
Print “underflow”
Return
2. Item = stack[top]
3. top = top - 1
4. Return
DISPLAY
1. If top = - 1
Print “underflow”
2. repeat step 3 for i = top to i >= 0
3. Print stack[i]
4. Return
#include<stdio.h>
#include<conio.h>
#define MAXSIZE 10
void push();
int pop();
void traverse();
int stack[MAXSIZE];
int Top=-1;
void main()
{
int choice;
char ch;
do
{
clrscr();
printf("\n1. PUSH ");
printf("\n2. POP ");
printf("\n3. TRAVERSE ");
printf("\nEnter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: printf("\nThe deleted element is %d",pop());
break;
case 3: traverse();
break;
default: printf("\nYou Entered Wrong Choice");
}
printf("\nDo You Wish To Continue (Y/N)");
fflush(stdin);
scanf("%c",&ch);
}
while(ch=='Y' || ch=='y');
}
void push()
{
int item;
if(Top == MAXSIZE - 1)
{
printf("\nThe Stack Is Full");
getch();
exit(0);
}
else
{
printf("Enter the element to be inserted");
scanf("%d",&item);
Top= Top+1;
stack[Top] = item;
}
}
int pop()
{
int item;
if(Top == -1)
{
printf("The stack is Empty");
getch();
exit(0);
}
else
{
item = stack[Top];
Top = Top-1;
}
return(item);
}
void traverse()
{
int i;
if(Top == -1)
{
printf("The Stack is Empty");
getch();
exit(0);
}
else
{
for(i=Top;i>=0;i--)
{
printf("Traverse the element");
printf("\n%d",stack[i]);
}
}
}
PRACTICAL-8
ALGORITHM
PUSH( )
1. t = newnode( )
2. Enter info to be inserted
3. Read n
4. tinfo = n
5. tnext = top
6. top = t
7. Return
POP( )
1. If (top = NULL)
Print “ underflow”
Return
2. x = top
3. top = top next
4. delnode(x)
5. Return
// stack using linked list//
#include<stdio.h>
#include<conio.h>
struct stack
{
int no;
struct stack *next;
}
*start=NULL;
typedef struct stack st;
void push();
int pop();
void display();
void main()
{
char ch;
int choice,item;
do
{
clrscr();
printf("\n 1: push");
printf("\n 2: pop");
printf("\n 3: display");
printf("\n Enter your choice");
scanf("%d",&choice);
switch (choice)
{
case 1: push();
break;
case 2: item=pop();
printf("The delete element in %d",item);
break;
case 3: display();
break;
default : printf("\n Wrong choice");
};
printf("\n do you want to continue(Y/N)");
fflush(stdin);
scanf("%c",&ch);
}
while (ch=='Y'||ch=='y');
}
void push()
{
st *node;
node=(st *)malloc(sizeof(st));
printf("\n Enter the number to be insert");
scanf("%d",&node->no);
node->next=start;
start=node;
}
int pop()
{
st *temp;
temp=start;
if(start==NULL)
{
printf("stack is already empty");
getch();
exit();
}
else
{
start=start->next;
free(temp);
}
return(temp->no);
}
void display()
{
st *temp;
temp=start;
while(temp->next!=NULL)
{
printf("\nno=%d",temp->no);
temp=temp->next;
}
printf("\nno=%d",temp->no);
}
PRACTICAL-9
Regular Expressions
Each expression denotes a language, and the following rules are given for the construction of
the denoted languages along with the regular-expression construction rules.
NFA
NFA stands for nondeterministic finite-state automata. NFA can be seen as a special kind
of final state machine, which is in a sense an abstract model of a machine with a primitive
internal memory. Let us look at the mathematical definition of NFA.
If we would explain the above definition to a 12 year old, we could say that an NFA is a set
‘S’ of states that are connected by function ‘f’ (maybe to a smarter 12 year old). NFAs are
represented in two formats: Table and Graph.
ALGORITHM
Method: We first decompose R into its primitive components. For each component we
construct a finite automaton inductively, as follows. Parts 1) and 2) form the basis and part
3) is the induction.
ε
i f
a
i` f`
Each time we need a new state, we give that state a new name. Even if a appears several
times in the regular expression R, we give each instance of a a separate finite automaton with
its own states. In this way, no two states generated either for the basis components to follow
have the same name.
For all regular expressions we construct an NFA with one initial and one final state, and with
the extra properties that no more than two edges leave any state. The limit of two on the
number of edges leaving each state is a convenience that allows an efficient
representation of the transition function of the automaton. We observe that each of the above
properties holds for the basis automata constructed in 1) and 2).
Conversion from NFA to DFA:
Є
2 3
a
Є a b b
Є Є Є
0 1 8 9 10
6 7
Є
Є
b
4 5
The state of DFA represents subset of all states of the NFA this algorithm is often called
subset construction.
To construct equivalent DFA we need to make set of states of all those states that are
reachable with a € transaction. To do this we construct a function to € - closure.
€ - closure(s) can be defined as a set of all those states that can be reached from s on €
transaction alone. If T is a set of states then € - closure(T) is just the union over all states s in T
of € -closure(s).
In algorithmic form of the same is:
begin
Push all states in T onto StACK; Є-
closure(T) := T;
While STACK not empty do
begin
pop s, the top element of STACK, off of STACk; for
each state t with an edge from s to t labeled € do if t is
not in Є-closure(T) do
begin
add t to Є-closure(T);
push t onto STACK
end
end
end
Now in the given example the initial state of N is 0 now starting with the state and moving
towards the DFA. We will first find out all the states of DFA by applying the algorithm and
then we will make a table and transition diagram of DFA.
0
Є-closure
0,1,2,4,7 A
a b
3,8 5
Є-closure
B 1,2,3,4,6,7,8 1,2,4,5,6,7 C
a b
b a
a b
3,8 5
Є-closure
B C
Transition Table:
States Input
a b
A B C
B B D
C B C
D B E
E B C
(Final State)
Transition Diagram:
a b
a B D
a
A b
a
a
E
b C
b
b
MINIMISATION OF DFA
The DFA produced form NFA have some states which can be removed without any
change to the functionality of the FA. To do this we the following method:
INPUT: A DFA M with set of states S inputs ∑ , transition defined on all states and
inputs, initial state S0 and set of final states F.
OUTPUT: A DFA M’ expecting the same language as M and having as few states as
possible.
After getting the pairs we look for their representation i.e. if there is a group of more than
one state than it is represented by the initial and final state if any of them is present
otherwise any of the state can represent the whole group and even a new representation
can be formed.
A,B,C,D E
Subgroup Making
A,B,C D E
Subgroup Making
A,C B D E
Representing
A B D E
States Input
a b
A B A
B B D
D B E
E B A
(Final State)
New Transition Diagram:
a
a
b
B
A
b b
a
a
E D
b