You are on page 1of 26

INDEX

Name: Manik Mittal


Course: B.Tech-CSE
Batch: 2014-2018
Semester: VII
Subject: Compiler Construction Lab

Date of Date of
Prog.
Name of the program Experiment Submission Signature
No.

1 WAP to check whether string is accepted or not


for entered grammar

2 WAP to convert Infix to Postfix notation

3 WAP to convert Infix to Prefix notation

4
WAP to find number of Tokens in an expression.

5 WAP to convert Regular Expression to NFA.

6 WAP to convert NFA to DFA.

WAP to calculate LEADING and TRAILING of


7 a grammar

WAP to calculate FIRST and FOLLOW of a


8 grammar

9 WAP to implement shift reduce parser

WAP to implement top down parser


10
Program no .1.:
AIM: WAP to check whether string is accepted or not for entered grammar

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
int main()
{
char string[20];
int state=0,count=0;
printf("the grammar is: S->aS, S->Sb, S->ab \n");
printf("enter the string to be checked \n");
gets(string);
while(string[count]!='\0')
{
switch(state)
{
case 0: if (string[count]=='a')
state=1;
else
state=3;
break;
case 1: if (string[count]=='a')
state=1;
else if(string[count]=='b')
state=2;
else
state=3;
break;
case 2: if (string[count]=='b')
state=2;
else
state=3;
break;
default: break;
}
count++;
if(state==3)
break;
}
if(state==2)
printf("string is accepted");
else
printf("string is not accepted");
getch();
}
OUTPUT:
Program no .2:

AIM: WAP to convert Infix to Postfix notation.

PROGRAM

#include<stdio.h>
#include <ctype.h>
char stack[20];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
}
main()
{
char exp[20];
char *e, x;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority
(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
}

OUTPUT:
Program no .3:
AIM: WAP to convert Infix to Prefix notation

PROGRAM

#define SIZE 50 /* Size of Stack */


#include<string.h>
#include <ctype.h>
#include<stdio.h>
char s[SIZE]; int top=-1; /* Global declarations */
push(char elem)
{ /* Function for PUSH operation */
s[++top]=elem;
}
char pop()
{ /* Function for POP operation */
return(s[top--]);
}
int pr(char elem)
{ /* Function for precedence */
switch(elem)
{
case '#': return 0;
case ')': return 1;
case '+':
case '-': return 2;
case '*':
case '/':return 3;
}
}
main()
{ /* Main Program */
char infx[50],prfx[50],ch,elem;
int i=0,k=0;
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
strrev(infx);
while( (ch=infx[i++]) != '\0')
{
if( ch == ')')
push(ch);
else if(isalnum(ch))
prfx[k++]=ch;
else if( ch == '(')
{
while( s[top] != ')')
prfx[k++]=pop();
elem=pop(); /* Remove ) */
}
else
{ /* Operator */
while( pr(s[top]) >= pr(ch) )
prfx[k++]=pop(); push(ch);
}
}
while( s[top] != '#') /* Pop from stack till empty */
prfx[k++]=pop();
prfx[k]='\0'; /* Make prfx as valid string */
strrev(prfx);
strrev(infx);
printf("\n\nGiven Infix Expn: %s \nPrefix Expn: %s\n",infx,prfx);
}
OUTPUT:
Program no .4:

AIM: WAP to find number of Tokens in an expression.

PROGRAM

import java.util.*;

public class StringTokenizerDemo {


public static void main(String[] args) {
// creating string tokenizer
Scanner sc = new Scanner(System.in);

String str = sc.nextLine();

String arr[] = str.split(" ");

// counting tokens
System.out.println("Total tokens : " + arr.length);
}
}

OUTPUT:
Program no .5:
AIM: WAP to convert Regular Expression to NFA

PROGRAM

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>

int main()
{
char m[20],t[10][10];
int n,i,j,r=0,c=0;
printf("\n\t\t\t\tSIMULATION OF NFA");
printf("\n\t\t\t\t*****************");
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
t[i][j]=' ';
}
}
printf("\n\nEnter a regular expression:");
scanf("%s",m);
n=strlen(m);
for(i=0;i<n;i++)
{
switch(m[i])
{
case '|' : {
t[r][r+1]='E';
t[r+1][r+2]=m[i-1];
t[r+2][r+5]='E';
t[r][r+3]='E';
t[r+4][r+5]='E';
t[r+3][r+4]=m[i+1];
r=r+5;
break;
}
case '*':{
t[r-1][r]='E';
t[r][r+1]='E';
t[r][r+3]='E';
t[r+1][r+2]=m[i-1];
t[r+2][r+1]='E';
t[r+2][r+3]='E';
r=r+3;
break;
}
case '+': {
t[r][r+1]=m[i-1];
t[r+1][r]='E';
r=r+1;
break;
}
default:
{

if(c==0)
{
if((isalpha(m[i]))&&(isalpha(m[i+1])))
{
t[r][r+1]=m[i];
t[r+1][r+2]=m[i+1];
r=r+2;
c=1;
}
c=1;
}
else if(c==1)
{
if(isalpha(m[i+1]))
{
t[r][r+1]=m[i+1];
r=r+1;
c=2;
}
}
else
{
if(isalpha(m[i+1]))
{
t[r][r+1]=m[i+1];
r=r+1;
c=3;
}
}
}
break;
}
}
printf("\n");
for(j=0;j<=r;j++)
printf(" %d",j);
printf("\n___________________________________\n");
printf("\n");
for(i=0;i<=r;i++)
{
for(j=0;j<=r;j++)
{
printf(" %c",t[i][j]);
}
printf(" | %d",i);
printf("\n");
}
printf("\nStart state: 0\nFinal state: %d",i-1);
getch();
}

OUTPUT:
Program no .6:
AIM: WAP to convert NFA to DFA

PROGRAM :

#include <stdio.h>
#include <string.h>
#define STATES 256
#define SYMBOLS 20
int N_symbols;
int NFA_states;
char *NFAtab[STATES][SYMBOLS];

int DFA_states; /* number of DFA states */


int DFAtab[STATES][SYMBOLS];

/*Print state-transition table.*/


void put_dfa_table(
int tab[][SYMBOLS], /* DFA table */
int nstates, /* number of states */
int nsymbols) /* number of input symbols */
{
int i, j;

puts("STATE TRANSITION TABLE");

/* input symbols: '0', '1', ... */


printf(" | ");
for (i = 0; i < nsymbols; i++) printf(" %c ", '0'+i);

printf("\n-----+--");
for (i = 0; i < nsymbols; i++) printf("-----");
printf("\n");

for (i = 0; i < nstates; i++) {


printf(" %c | ", 'A'+i); /* state */
for (j = 0; j < nsymbols; j++)
printf(" %c ", 'A'+tab[i][j]);
printf("\n");
}
}

/*Initialize NFA table.*/


void init_NFA_table()
{
/*

NFAtab[0][0] = "01";
NFAtab[0][1] = "0";
NFAtab[1][0] = "";
NFAtab[1][1] = "01";
NFA_states = 2;
DFA_states = 0;
N_symbols = 2;
*/
NFAtab[0][0] = "12";
NFAtab[0][1] = "13";
NFAtab[1][0] = "12";
NFAtab[1][1] = "13";
NFAtab[2][0] = "4";
NFAtab[2][1] = "";
NFAtab[3][0] = "";
NFAtab[3][1] = "4";
NFAtab[4][0] = "4";
NFAtab[4][1] = "4";

NFA_states = 5;
DFA_states = 0;
N_symbols = 2;
}

/*String 't' is merged into 's' in an alphabetical order.*/


void string_merge(char *s, char *t)
{
char temp[STATES], *r=temp, *p=s;

while (*p && *t) {


if (*p == *t) {
*r++ = *p++; t++;
} else if (*p < *t) {
*r++ = *p++;
} else
*r++ = *t++;
}
*r = '\0';

if (*p) strcat(r, p);


else if (*t) strcat(r, t);

strcpy(s, temp);
}

/*Get next-state string for current-state string.*/


void get_next_state(char *nextstates, char *cur_states,
char *nfa[STATES][SYMBOLS], int n_nfa, int symbol)
{
int i;
char temp[STATES];
temp[0] = '\0';
for (i = 0; i < strlen(cur_states); i++)
string_merge(temp, nfa[cur_states[i]-'0'][symbol]);
strcpy(nextstates, temp);
}
int state_index(char *state, char statename[][STATES], int *pn)
{
int i;
if (!*state) return -1; /* no next state */

for (i = 0; i < *pn; i++)


if (!strcmp(state, statename[i])) return i;
strcpy(statename[i], state); /* new state-name */
return (*pn)++;
}
/*
Convert NFA table to DFA table.
Return value: number of DFA states.
*/
int nfa_to_dfa(char *nfa[STATES][SYMBOLS], int n_nfa,
int n_sym, int dfa[][SYMBOLS])
{
char statename[STATES][STATES];
int i = 0; /* current index of DFA */
int n = 1; /* number of DFA states */

char nextstate[STATES];
int j;

strcpy(statename[0], "0"); /* start state */

for (i = 0; i < n; i++) { /* for each DFA state */


for (j = 0; j < n_sym; j++) { /* for each input symbol */
get_next_state(nextstate, statename[i], nfa, n_nfa, j);
dfa[i][j] = state_index(nextstate, statename, &n);
}
}
return n; /* number of DFA states */
}
int main()
{
init_NFA_table();
DFA_states = nfa_to_dfa(NFAtab, NFA_states, N_symbols, DFAtab);
put_dfa_table(DFAtab, DFA_states, N_symbols);
}

OUTPUT:
Program no .7:
AIM: WAP to calculate LEADING and TRAILING of a grammar

PROGRAM :

#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
int nt,t,top=0;
char s[50],NT[10],T[10],st[50],l[10][10],tr[50][50];
int searchnt(char a)
{
int count=-1,i;
for(i=0;i<nt;i++)
{
if(NT[i]==a)
return i;
}
return count;
}
int searchter(char a)
{
int count=-1,i;
for(i=0;i<t;i++)
{
if(T[i]==a)
return i;
}
return count;
}
void push(char a)
{
s[top]=a;
top++;
}
char pop()
{
top--;
return s[top];
}
void installl(int a,int b)

{
if(l[a][b]=='f')
{
l[a][b]='t';
push(T[b]);
push(NT[a]);
}
}
void installt(int a,int b)
{
if(tr[a][b]=='f')
{
tr[a][b]='t';
push(T[b]);
push(NT[a]);
}
}

int main()
{
int i,s,k,j,n;
char pr[30][30],b,c;
cout<<"Enter the no of productions:";
cin>>n;
cout<<"Enter the productions one by one\n";
for(i=0;i<n;i++)
cin>>pr[i];
nt=0;
t=0;
for(i=0;i<n;i++)
{
if((searchnt(pr[i][0]))==-1)
NT[nt++]=pr[i][0];
}
for(i=0;i<n;i++)
{
for(j=3;j<strlen(pr[i]);j++)
{
if(searchnt(pr[i][j])==-1)
{
if(searchter(pr[i][j])==-1)
T[t++]=pr[i][j];
}
}
}
for(i=0;i<nt;i++)
{
for(j=0;j<t;j++)
l[i][j]='f';
}
for(i=0;i<nt;i++)
{
for(j=0;j<t;j++)

tr[i][j]='f';
}
for(i=0;i<nt;i++)
{
for(j=0;j<n;j++)
{
if(NT[(searchnt(pr[j][0]))]==NT[i])
{
if(searchter(pr[j][3])!=-1)
installl(searchnt(pr[j][0]),searchter(pr[j][3]));
else
{
for(k=3;k<strlen(pr[j]);k++)
{
if(searchnt(pr[j][k])==-1)
{
installl(searchnt(pr[j][0]),searchter(pr[j][k]));
break;
}
}
}
}
}
}
while(top!=0)
{
b=pop();
c=pop();
for(s=0;s<n;s++)
{
if(pr[s][3]==b)
installl(searchnt(pr[s][0]),searchter(c));
}
}
for(i=0;i<nt;i++)
{
cout<<"Leading["<<NT[i]<<"]"<<"\t{";
for(j=0;j<t;j++)
{
if(l[i][j]=='t')
cout<<T[j]<<",";
}
cout<<"}\n";
}

top=0;
for(i=0;i<nt;i++)
{
for(j=0;j<n;j++)
{
if(NT[searchnt(pr[j][0])]==NT[i])
{
if(searchter(pr[j][strlen(pr[j])-1])!=-1)
installt(searchnt(pr[j][0]),searchter(pr[j][strlen(pr[j])-1]));
else
{
for(k=(strlen(pr[j])-1);k>=3;k--)
{
if(searchnt(pr[j][k])==-1)
{
installt(searchnt(pr[j][0]),searchter(pr[j][k]));
break;
}
}
}
}
}
}
while(top!=0)
{
b=pop();
c=pop();
for(s=0;s<n;s++)
{
if(pr[s][3]==b)
installt(searchnt(pr[s][0]),searchter(c));
}
}
for(i=0;i<nt;i++)
{
cout<<"Trailing["<<NT[i]<<"]"<<"\t{";
for(j=0;j<t;j++)
{
if(tr[i][j]=='t')
cout<<T[j]<<",";
}
cout<<"}\n";
}
getch();
}

OUTPUT:
Program no .8:
AIM: WAP to calculate FIRST and FOLLOW of a grammar

PROGRAM :

/* FIRST */

#include<stdio.h>
#include<ctype.h>
void FIRST(char[],char );
void addToResultSet(char[],char);
int numOfProductions;
char productionSet[10][10];
main()
{
int i;
char choice;
char c;
char result[20];
printf("How many number of productions ? :");
scanf(" %d",&numOfProductions);
for(i=0;i<numOfProductions;i++)//read production string eg: E=E+T
{
printf("Enter productions Number %d : ",i+1);
scanf(" %s",productionSet[i]);
}
do
{
printf("\n Find the FIRST of :");
scanf(" %c",&c);
FIRST(result,c); //Compute FIRST; Get Answer in 'result' array
printf("\n FIRST(%c)= { ",c);
for(i=0;result[i]!='\0';i++)
printf(" %c ",result[i]); //Display result
printf("}\n");
printf("press 'y' to continue : ");
scanf(" %c",&choice);
}
while(choice=='y'||choice =='Y');
}
/*
*Function FIRST:
*Compute the elements in FIRST(c) and write them
*in Result Array.
*/
void FIRST(char* Result,char c)
{
int i,j,k;
char subResult[20];
int foundEpsilon;
subResult[0]='\0';
Result[0]='\0';
//If X is terminal, FIRST(X) = {X}.
if(!(isupper(c)))
{
addToResultSet(Result,c);
return ;
}
//If X is non terminal
//Read each production
for(i=0;i<numOfProductions;i++)
{
//Find production with X as LHS
if(productionSet[i][0]==c)
{
//If X ? e is a production, then add e to FIRST(X).
if(productionSet[i][2]=='$') addToResultSet(Result,'$');
//If X is a non-terminal, and X ? Y1 Y2 Yk
//is a production, then add a to FIRST(X)
//if for some i, a is in FIRST(Yi),
//and e is in all of FIRST(Y1), , FIRST(Yi-1).
else
{
j=2;
while(productionSet[i][j]!='\0')
{
foundEpsilon=0;
FIRST(subResult,productionSet[i][j]);
for(k=0;subResult[k]!='\0';k++)
addToResultSet(Result,subResult[k]);
for(k=0;subResult[k]!='\0';k++)
if(subResult[k]=='$')
{
foundEpsilon=1;
break;
}
//No e found, no need to check next element
if(!foundEpsilon)
break;
j++;
}
}
}
}
return ;
}
/* addToResultSet adds the computed
*element to result set.
*This code avoids multiple inclusion of elements
*/
void addToResultSet(char Result[],char val)
{
int k;
for(k=0 ;Result[k]!='\0';k++)
if(Result[k]==val)
return;
Result[k]=val;
Result[k+1]='\0';
}

/* FOLLOW */

#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<ctype.h>
int n,m=0,p,i=0,j=0;
char a[10][10],followResult[10];
void follow(char c);
void first(char c);
void addToResult(char);
int main()
{
int i;
int choice;
char c,ch;
printf("Enter the no.of productions: ");
scanf("%d", &n);
printf(" Enter %d productions\nProduction with multiple terms should be give as separate productions \n",
n);
for(i=0;i<n;i++)
scanf("%s%c",a[i],&ch);
// gets(a[i]);
do
{
m=0;
printf("Find FOLLOW of -->");
scanf(" %c",&c);
follow(c);
printf("FOLLOW(%c) = { ",c);
for(i=0;i<m;i++)
printf("%c ",followResult[i]);
printf(" }\n");
printf("Do you want to continue(Press 1 to continue....)?");
scanf("%d%c",&choice,&ch);
}
while(choice==1);
}
void follow(char c)
{
if(a[0][0]==c)addToResult('$');
for(i=0;i<n;i++)
{
for(j=2;j<strlen(a[i]);j++)
{
if(a[i][j]==c)
{
if(a[i][j+1]!='\0')first(a[i][j+1]);
if(a[i][j+1]=='\0'&&c!=a[i][0])
follow(a[i][0]);
}
}
}
}
void first(char c)
{
int k;
if(!(isupper(c)))
//f[m++]=c;
addToResult(c);
for(k=0;k<n;k++)
{
if(a[k][0]==c)
{
if(a[k][2]=='$') follow(a[i][0]);
else if(islower(a[k][2]))
//f[m++]=a[k][2];
addToResult(a[k][2]);
else first(a[k][2]);
}
}
}
void addToResult(char c)
{
int i;
for( i=0;i<=m;i++)
if(followResult[i]==c)
return;
followResult[m++]=c;
}
OUTPUT:
Program no .9:

AIM: WAP to implement shift reduce parser.

PROGRAM :

#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char str[25],stk[25];
int i,j,t=0,l,r;
printf("Enter the String : ");
scanf("%s",&str);
l=strlen(str);
str[l]='$';
stk[t]='$';
printf("Stack\t\tString\t\tAction\n-----------------------------------\n ");

for(i=0;i<l;i++)
{
if(str[i]=='i')
{
t++;
stk[t]=str[i];
stk[t+1]=str[i+1];

for(j=0;j<=t+1;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+2;j<=l;j++)
printf("%c",str[j]);
printf("\t\tShift");
printf("\n ");
stk[t]='E';
i++;
}
else
{
t++;
stk[t]=str[i];
}
for(j=0;j<=t;j++)
printf("%c",stk[j]);
printf("\t\t ");
for(j=i+1;j<=l;j++)
printf("%c",str[j]);
if(stk[t]=='+' || stk[t]=='*')
printf("\t\tShift");
else
printf("\t\tReduce");
printf("\n ");
}

while(t>1)
{
if(stk[t]=='E' && (stk[t-1]=='+' || stk[t-1]=='*') && stk[t-2]=='E')
{
t-=2;

for(j=0;j<=t;j++)
printf("%c",stk[j]);
printf("\t\t");
printf(" %c",str[l]);
printf("\t\tReduce\n ");
}
else
t-=2;
}

if(t==1 && stk[t]!='+' && stk[t]!='*')


printf("\nThe Given String is Valid\n\n");
else
printf("\nThe Given String is Invalid\n\n");
getch();
}

OUTPUT:
Program no .10:

AIM: WAP to implement top down parser.

PROGRAM :

#include<stdio.h>
#include<string.h>

void check(void);
void set_value_backtracking(void);
void get_value_backtracking(void);
void display_output_string(void);

int iptr=0,optr=0,current_optr=0;
char output_string[20],current_output_string[20],input_string[20],temp_string[20];

int main(){
printf("\nEnter the string to check: ");
scanf("%s",input_string);
check();
return 0;}

void check(void){

int flag=1,rule2_index=1;
strcpy(output_string,"S");

printf("\nThe output string in different stages are:\n");

while(iptr<=strlen(input_string)){

if(strcmp(output_string,temp_string)!=0){
display_output_string();}

if((iptr!=strlen(input_string)) || (optr!=strlen(output_string))){
if(input_string[iptr]==output_string[optr]){
iptr=iptr+1;
optr=optr+1;}

else{
if(output_string[optr]=='S'){
memset(output_string,0,strlen(output_string));
strcpy(output_string,"cAd");}

else if(output_string[optr]=='A'){
set_value_backtracking();

if(rule2_index==1){
memset(output_string,0,strlen(output_string));
strcpy(output_string,"cabd");}
else{
memset(output_string,0,strlen(output_string));
strcpy(output_string,"cad");}}

else if(output_string[optr]=='b' && input_string[iptr]=='d'){


rule2_index=2;
get_value_backtracking();
iptr=iptr-1;}

else{
printf("\nThe given string, '%s' is invalid.\n\n",input_string);
break;}}}

else{
printf("\nThe given string, '%s' is valid.\n\n",input_string);
break;}}}

void set_value_backtracking(void){ //setting values for backtracking


current_optr=optr;
strcpy(current_output_string,output_string);
return;}

void get_value_backtracking(void){ //backtracking and obtaining previous values


optr=current_optr;
memset(output_string,0,strlen(output_string));
strcpy(output_string,current_output_string);
return;}

void display_output_string(void){
printf("%s\n",output_string);
memset(temp_string,0,strlen(temp_string));
strcpy(temp_string,output_string);
return;}

OUTPUT:

You might also like